﻿using Comm100.Framework.Domain.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bot.Domain.Entities;
using Bot.Domain.Interfaces;
using Bot.Domain.Bo;
using Castle.Windsor;
using Bot.Domain.Specifications;
using Bot.Domain.Bot;
using Bot.Domain.Enum;
using System.IO;
using System.Reflection;
using Bot.Domain.BotImport;
using Newtonsoft.Json;
using AutoMapper;
using System.Text.RegularExpressions;

namespace Bot.Domain.Categories.Service
{
    public class ChatbotDomainService : IChatbotDomainService
    {
        private IWindsorContainer _container;
        private readonly IRepository<Guid, Chatbot> _repository;
        public IMapper Mapper { get; set; }

        public ChatbotDomainService(IRepository<Guid, Chatbot> repository, IWindsorContainer container)
        {
            this._repository = repository;
            this._container = container;
        }

        public Chatbot Create(Chatbot chatbot, bool isTest, string projectId)
        {
            int siteId = 1000007; //从 token 取
            BotDto dto = GetDefaultBotSettings(chatbot.Language.ToLower().Trim());
            
            chatbot.Id = Guid.NewGuid();
            
            IDialogflowDomainService dialogflowDomainService = _container.Resolve<IDialogflowDomainService>();
            IBotApiService botApiService = _container.Resolve<IBotApiService>();
            IPrebuiltEntityDomainService prebuiltEntityDomainService = _container.Resolve<IPrebuiltEntityDomainService>();
            IQuickReplyDomainService quickReplyDomainService = _container.Resolve<IQuickReplyDomainService>();
            IEntityDomainService entityDomainService = _container.Resolve<IEntityDomainService>();
            
            Dialogflow dialogflow = null;

            if (dto != null)
            {
                if (chatbot.EngineType.Equals(EnumBotType.comm100Bot))
                {               
                    if (string.IsNullOrEmpty(projectId))
                    {
                        var dialogflows = dialogflowDomainService.GetByIsTestAccount(isTest).ToList();
                        dialogflow = Utils.GetRandomItemFromList<Dialogflow>(dialogflows);
                        dialogflow.SiteId = siteId;
                        dialogflow.BotId = chatbot.Id;

                        chatbot.DialogFlowProjectId = dialogflow.ProjectId;
                    }
                    chatbot.IsTrained = false;
                    chatbot.MessageWhenNotHelpful = dto.NotHelpfulMessage;
                    chatbot.IfIncludeContactAgentOptionWhenNotHelpful = dto.IsShowAgentLinkWhenNotHelpful;
                    chatbot.ConsecutiveTimesOfPossibleAnswers = dto.PossibleResponsesThreshold;
                    chatbot.MessageAfterVisitorChooseToContactAgent = dto.TransferAgentMessage;
                    chatbot.ContactAgentButtonTextWhenOnline = dto.TextWhenAgentIsOnline;
                    chatbot.ContactAgentButtonTextWhenOffline = dto.TextWhenAgentIsOffline;
                    chatbot.FormSubmitButtonText = dto.SubmitButtonText;
                    chatbot.FormCancelButtonText = dto.CancelButtonText;
                    chatbot.FormConfirmButtonText = dto.ConfirmButtonText;
                    chatbot.HighConfidenceScore = 40;
                    chatbot.NoAnswerScore = 10;
                    chatbot.OwnBotConfig = "";
                    chatbot.ThirdPartyWebhookId = null;
                    if (chatbot.GreetingMessageInChannels == null)
                    {
                        chatbot.GreetingMessageInChannels = new List<GreetingMessageInChannel> { };
                    }
                    if (!chatbot.GreetingMessageInChannels.Any(f => f.Channel == "default"))
                    {
                        var textVariants = new List<string> { };
                        foreach (var response in dto.GreetingMessage["default"])
                        {
                            if (response.Type == EnumAnswerType.text)
                            {
                                IntentResponsesDto intentResponsesDto = response.Content as IntentResponsesDto;
                                IntentTextResponsesDto intentTextResponsesDto = intentResponsesDto.Content as IntentTextResponsesDto;

                                textVariants.Concat(intentTextResponsesDto.Texts);
                            }
                        }
                        chatbot.GreetingMessageInChannels.Add(new GreetingMessageInChannel
                        {
                            Channel = "default",
                            Responses = new List<Response>
                            {
                                new Response
                                {
                                   Type = EnumAnswerType.text,
                                   TextVariants = JsonConvert.SerializeObject(textVariants),
                                }
                            }
                        });
                    }
                }
                else if (chatbot.EngineType.Equals(EnumBotType.comm100OwnBot))
                {
                    chatbot.IsTrained = false;
                    chatbot.MessageWhenNotHelpful = dto.NotHelpfulMessage;
                    chatbot.IfIncludeContactAgentOptionWhenNotHelpful = dto.IsShowAgentLinkWhenNotHelpful;
                    chatbot.ConsecutiveTimesOfPossibleAnswers = dto.PossibleResponsesThreshold;
                    chatbot.MessageAfterVisitorChooseToContactAgent = dto.TransferAgentMessage;
                    chatbot.ContactAgentButtonTextWhenOnline = dto.TextWhenAgentIsOnline;
                    chatbot.ContactAgentButtonTextWhenOffline = dto.TextWhenAgentIsOffline;
                    chatbot.FormSubmitButtonText = dto.SubmitButtonText;
                    chatbot.FormCancelButtonText = dto.CancelButtonText;
                    chatbot.FormConfirmButtonText = dto.ConfirmButtonText;
                    chatbot.HighConfidenceScore = 40;
                    chatbot.NoAnswerScore = 10;  
                    chatbot.OwnBotConfig = "";
                    chatbot.ThirdPartyWebhookId = null;
                    chatbot.DialogFlowProjectId = "-";
                    if (chatbot.GreetingMessageInChannels == null)
                    {
                        chatbot.GreetingMessageInChannels = new List<GreetingMessageInChannel> { };
                    }
                    if (!chatbot.GreetingMessageInChannels.Any(f => f.Channel == "default"))
                    {
                        var textVariants = new List<string> { };
                        foreach (var response in dto.GreetingMessage["default"])
                        {
                            if (response.Type == EnumAnswerType.text)
                            {
                                IntentTextResponsesDto intentTextResponsesDto = response.Content as IntentTextResponsesDto;

                                textVariants.AddRange(intentTextResponsesDto.Texts);
                            }
                        }
                        chatbot.GreetingMessageInChannels.Add(new GreetingMessageInChannel
                        {
                            Channel = "default",
                            Responses = new List<Response>
                            {
                                new Response
                                {
                                   Type = EnumAnswerType.text,
                                   TextVariants = JsonConvert.SerializeObject(textVariants),
                                }
                            }
                        });
                    }
                }
                else
                {
                    chatbot.IsTrained = false;
                    chatbot.MessageWhenNotHelpful = string.Empty;
                    chatbot.IfIncludeContactAgentOptionWhenNotHelpful = false;
                    chatbot.ConsecutiveTimesOfPossibleAnswers = 0;
                    chatbot.MessageAfterVisitorChooseToContactAgent = string.Empty;
                    chatbot.ContactAgentButtonTextWhenOnline = string.Empty;
                    chatbot.ContactAgentButtonTextWhenOffline = string.Empty;
                    chatbot.FormSubmitButtonText = string.Empty;
                    chatbot.FormCancelButtonText = string.Empty;
                    chatbot.FormConfirmButtonText = string.Empty;
                    chatbot.HighConfidenceScore = 0;
                    chatbot.NoAnswerScore = 0;
                    chatbot.LastUpdatedTime = DateTime.UtcNow;
                    chatbot.OwnBotConfig = "";
                    chatbot.DialogFlowProjectId = "";
                }
                chatbot.SiteId = siteId;
                chatbot.IsDeleted = false;
                chatbot.LastUpdatedTime = DateTime.UtcNow;
                if (!chatbot.AvatarId.HasValue)
                {
                    chatbot.AvatarId = Guid.Parse("9B096C2E-9E20-EA11-80DB-000D3A40AE7F");//默认的图片ID
                }
            }

            chatbot = _repository.Create(chatbot); //添加 chatbot

            if (chatbot.EnabledChannels != null)
            {
                IEnabledChannelDomainService enabledChannelDomainService = _container.Resolve<IEnabledChannelDomainService>();
                var enabledChannels = enabledChannelDomainService.GetByBotId(chatbot.Id).ToList();
                foreach (var enabledChannel in chatbot.EnabledChannels)
                {
                    if(!enabledChannels.Any(f=>f.Channel == enabledChannel))
                    {
                        EnabledChannel enabledChannelCreate = new EnabledChannel
                        {
                            Id = Guid.NewGuid(),
                            BotId = chatbot.Id,
                            Channel = enabledChannel,
                        };
                        enabledChannelDomainService.Create(enabledChannelCreate);

                        enabledChannels.Add(enabledChannelCreate);
                    }
                }
            }

            IGreetingMessageInChannelDomainService greetingMessageInChannelDomainService = _container.Resolve<IGreetingMessageInChannelDomainService>();
            IIntentDomainService intentDomainService = _container.Resolve<IIntentDomainService>();
            INoAnswerMessageInChannelDomainService noAnswerMessageInChannelDomainService = _container.Resolve<INoAnswerMessageInChannelDomainService>();
            IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService = _container.Resolve<IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService>();

            AddGreetingMessage(chatbot.Id, chatbot.GreetingMessageInChannels,
                greetingMessageInChannelDomainService);

            AddUnrecognizedMessage(chatbot.Id, chatbot.NoAnswerMessageInChannels, chatbot.MessageAfterSeveralConsecutivePossibleAnswersInChannels,
                noAnswerMessageInChannelDomainService,
                messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService);


            if (chatbot.EngineType.Equals(EnumBotType.comm100Bot))
            {
                //InUse
                var dialogflowUpdateBo = Mapper.Map<DialogflowUpdateBo>(dialogflow);
                dialogflowDomainService.Update(dialogflowUpdateBo);

                var prebuilts = prebuiltEntityDomainService.List(chatbot.Language).ToList();

                entityDomainService.BatchInsertPrebuiltEntities(siteId, dto.Id, prebuilts);

                //2019.7.25 创建一个默认的Default的QuickReply
                quickReplyDomainService.Create(new QuickReply {
                    Id = Guid.NewGuid(),
                    BotId=chatbot.Id,
                    Type = EnumReplyType.canned,
                    Name= "Default",
                    Items=new List<QuickReplyItem> { 
                        new QuickReplyItem
                        {
                            Type = EnumQuickReplyType.contactAgent,
                            Text = chatbot.ContactAgentButtonTextWhenOnline
                        }
                    }
                });

                BotImportDataQueue botImportDataQueue = new BotImportDataQueue
                {
                    SiteId = siteId,
                    BotId = dto.Id,
                    AppId = chatbot.DialogFlowProjectId,
                    BotImportData = new BotImportDataEx
                    {
                        Bot = new BotTypeEx
                        {
                            Language = dto.Language,
                            Category = new BotCategoryTypeEx[] {
                                        },
                            Entity = new BotEntityTypeEx[] { }
                        }
                    }
                };

                botApiService.RestoreBot(dto, botImportDataQueue).RunSynchronously();

                //导入chit_chat
                string filePath = CopyChitChatFile(siteId, dto.Language);
                if (!string.IsNullOrEmpty(filePath))
                {
                    Guid headGuid = Guid.NewGuid();
                    var importResult = intentDomainService.Import(headGuid, filePath, chatbot, EnumImportMode.overwrite);

                    while (!(importResult.Status == EnumOperationStatus.Succeeded ||
                        importResult.Status == EnumOperationStatus.Failed))
                    {
                        importResult = intentDomainService.Import(headGuid, filePath, chatbot, EnumImportMode.overwrite);
                    }
                }

            }
            else if (chatbot.EngineType.Equals(EnumBotType.comm100OwnBot))
            {
                var prebuilts = prebuiltEntityDomainService.List(chatbot.Language).ToList();
                entityDomainService.BatchInsertPrebuiltEntities(siteId, chatbot.Id, prebuilts);
                //2019.7.25 创建一个默认的Default的QuickReply
                quickReplyDomainService.Create(new QuickReply
                {
                    Id = Guid.NewGuid(),
                    BotId = chatbot.Id,
                    Type = EnumReplyType.canned,
                    Name = "Default",
                    Items = new List<QuickReplyItem> {
                        new QuickReplyItem
                        {
                            Type = EnumQuickReplyType.contactAgent,
                            Text = chatbot.ContactAgentButtonTextWhenOnline
                        }
                    }
                });
                BotImportDataQueue botImportDataQueue = new BotImportDataQueue
                {
                    SiteId = siteId,
                    BotId = chatbot.Id,
                    AppId = chatbot.DialogFlowProjectId,
                    BotImportData = new BotImportDataEx
                    {
                        Bot = new BotTypeEx
                        {
                            Language = dto.Language,
                            Category = new BotCategoryTypeEx[] {
                                        },
                            Entity = new BotEntityTypeEx[] { }
                        }
                    }
                };

                var result = botApiService.RestoreBot(dto, botImportDataQueue).Result;

                //导入chit_chat
                string filePath = CopyChitChatFile(siteId, dto.Language);
                if (!string.IsNullOrEmpty(filePath))
                {
                    Guid headGuid = Guid.NewGuid();
                    var importResult = intentDomainService.Import(headGuid, filePath, chatbot, EnumImportMode.overwrite);

                    while (!(importResult.Status == EnumOperationStatus.Succeeded ||
                        importResult.Status == EnumOperationStatus.Failed))
                    {
                        importResult = intentDomainService.Import(headGuid, filePath, chatbot, EnumImportMode.overwrite);
                    }
                }
            }            

            return Get(chatbot.Id, include: "greetingMessageInChannels");
        }

        public Chatbot Get(Guid id, string include = "")
        {
            var chatbot = _repository.Get(id);

            if (chatbot != null
                && !string.IsNullOrEmpty(include))
            {
                //对象化
                IImageDomainService imageDomainService = _container.Resolve<IImageDomainService>();
                IWebhookDomainService webhookDomainService = _container.Resolve<IWebhookDomainService>();
                IGreetingMessageInChannelDomainService greetingMessageInChannelDomainService = _container.Resolve<IGreetingMessageInChannelDomainService>();
                INoAnswerMessageInChannelDomainService noAnswerMessageInChannelDomainService = _container.Resolve<INoAnswerMessageInChannelDomainService>();
                IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService = _container.Resolve<IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService>();

                if (chatbot.AvatarId.HasValue && chatbot.AvatarId != Guid.Empty)
                {
                    var image = imageDomainService.Get(chatbot.AvatarId.Value);
                    chatbot.Avatar = image;
                }

                LoadGreetingMessageInChannel(chatbot,
                    greetingMessageInChannelDomainService,
                    include);

                LoadNoAnswerMessageInChannel(chatbot,
                    noAnswerMessageInChannelDomainService);

                LoadMessageAfterSeveralConsecutivePossibleAnswersInChannel(chatbot,
                    messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService);

                if (chatbot.ThirdPartyWebhookId.HasValue)
                {
                    var webhook = webhookDomainService.Get(chatbot.ThirdPartyWebhookId.Value);
                    chatbot.ThirdPartyWebhook = webhook;
                }

                IEnabledChannelDomainService enabledChannelDomainService = _container.Resolve<IEnabledChannelDomainService>();
                var enabledChannels = enabledChannelDomainService.GetByBotId(chatbot.Id).ToList();
                chatbot.EnabledChannels = enabledChannels.Select(a => a.Channel).ToList();
            }

            return chatbot;
        }

        public Chatbot Update(Guid id, ChatbotUpdateBo bo)
        {
            Chatbot chatbot = _repository.Get(bo.Id);

            chatbot.AvatarId = bo.AvatarId;
            chatbot.Name = bo.Name;
            chatbot.ThirdPartyWebhookId = bo.ThirdPartyWebhookId;
            chatbot.IsTrained = bo.IsTrained;
            chatbot.MessageWhenNotHelpful = bo.MessageWhenNotHelpful;
            chatbot.IfIncludeContactAgentOptionWhenNotHelpful = bo.IfIncludeContactAgentOptionWhenNotHelpful;
            chatbot.MessageWhenProvidingPossibleAnswer = bo.MessageWhenProvidingPossibleAnswer;
            chatbot.ConsecutiveTimesOfPossibleAnswers = bo.ConsecutiveTimesOfPossibleAnswers;
            chatbot.MessageAfterVisitorChooseToContactAgent = bo.MessageAfterVisitorChooseToContactAgent;
            chatbot.ContactAgentButtonTextWhenOnline = bo.ContactAgentButtonTextWhenOnline;
            chatbot.ContactAgentButtonTextWhenOffline = bo.ContactAgentButtonTextWhenOffline;
            chatbot.FormSubmitButtonText = bo.FormSubmitButtonText;
            chatbot.FormCancelButtonText = bo.FormCancelButtonText;
            chatbot.FormConfirmButtonText = bo.FormConfirmButtonText;
            chatbot.HighConfidenceScore = bo.HighConfidenceScore;
            chatbot.NoAnswerScore = bo.NoAnswerScore;
            chatbot.LastUpdatedTime = DateTime.UtcNow;
            chatbot.OwnBotConfig = bo.OwnBotConfig;

            if (chatbot.EnabledChannels != null)
            {
                IEnabledChannelDomainService enabledChannelDomainService = _container.Resolve<IEnabledChannelDomainService>();
                var enabledChannels = enabledChannelDomainService.GetByBotId(chatbot.Id).ToList();

                List<Guid> enabledChannelIds = new List<Guid> { };
                foreach (var enabledChannel in chatbot.EnabledChannels)
                {
                    var enabledChannelFind = enabledChannels.FirstOrDefault(f => f.Channel == enabledChannel);

                    if (enabledChannelFind == null)
                    {
                        EnabledChannel enabledChannelCreate = new EnabledChannel
                        {
                            Id = Guid.NewGuid(),
                            BotId = chatbot.Id,
                            Channel = enabledChannel,
                        };
                        enabledChannelDomainService.Create(enabledChannelCreate);

                        enabledChannels.Add(enabledChannelCreate);

                        enabledChannelIds.Add(enabledChannelCreate.Id);
                    }
                    else
                    {
                        enabledChannelIds.Add(enabledChannelFind.Id);
                    }
                }

                foreach(var channel in enabledChannels)
                {
                    if (!enabledChannelIds.Contains(channel.Id))
                    {
                        enabledChannelDomainService.Delete(channel.Id);
                    }
                }
            }

            IGreetingMessageInChannelDomainService greetingMessageInChannelDomainService = _container.Resolve<IGreetingMessageInChannelDomainService>();
            INoAnswerMessageInChannelDomainService noAnswerMessageInChannelDomainService = _container.Resolve<INoAnswerMessageInChannelDomainService>();
            IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService = _container.Resolve<IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService>();

            AddGreetingMessage(chatbot.Id, Mapper.Map<ICollection<GreetingMessageInChannel>>(bo.GreetingMessageInChannels),
                greetingMessageInChannelDomainService);

            AddUnrecognizedMessage(chatbot.Id, Mapper.Map<ICollection<NoAnswerMessageInChannel>>(bo.NoAnswerMessageInChannels), Mapper.Map <ICollection<MessageAfterSeveralConsecutivePossibleAnswersInChannel>> (bo.MessageAfterSeveralConsecutivePossibleAnswersInChannels),
                noAnswerMessageInChannelDomainService,
                messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService);

            _repository.Update(chatbot);

            return Get(chatbot.Id, include: "greetingMessageInChannels");

        }

        public IEnumerable<Chatbot> List(string include, string channel)
        {
            int siteId = 1000007; //从 Token 取
            var chatbots = _repository.List(new ChatbotFilterSpecification(siteId));

            if (chatbots != null && chatbots.Count>0)
            {
                IGreetingMessageInChannelDomainService greetingMessageInChannelDomainService = _container.Resolve<IGreetingMessageInChannelDomainService>();
                INoAnswerMessageInChannelDomainService noAnswerMessageInChannelDomainService = _container.Resolve<INoAnswerMessageInChannelDomainService>();
                IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService = _container.Resolve<IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService>();
                IImageDomainService imageDomainService = _container.Resolve<IImageDomainService>();
                IWebhookDomainService webhookDomainService = _container.Resolve<IWebhookDomainService>();

                foreach (var chatbot in chatbots)
                {
                    if (chatbot.AvatarId.HasValue 
                        && chatbot.AvatarId != Guid.Empty
                        && !string.IsNullOrEmpty(include)
                        && include.Split(',').Contains("avatar"))
                    {
                        var image = imageDomainService.Get(chatbot.AvatarId.Value);
                        chatbot.Avatar = image;
                    }
                    if (chatbot.ThirdPartyWebhookId.HasValue
                        && chatbot.ThirdPartyWebhookId != Guid.Empty
                        && !string.IsNullOrEmpty(include)
                        && include.Split(',').Contains("thirdPartyWebhook"))
                    {
                        var webhook = webhookDomainService.Get(chatbot.ThirdPartyWebhookId.Value);
                        chatbot.ThirdPartyWebhook = webhook;
                    }

                    if (!string.IsNullOrEmpty(include) 
                        && include.Equals("greetingMessageInChannels"))
                    {
                        chatbot.GreetingMessageInChannels = greetingMessageInChannelDomainService.GetByBotId(chatbot.Id, include);
                        if (chatbot.GreetingMessageInChannels != null
                            && !string.IsNullOrEmpty(channel))
                        {
                            chatbot.GreetingMessageInChannels = chatbot.GreetingMessageInChannels.Where(f => f.Channel == channel).ToList();
                        }
                    }              

                    if (!string.IsNullOrEmpty(include) 
                        && include.Equals("noAnswerMessageInChannels"))
                    {
                        LoadNoAnswerMessageInChannel(chatbot,
                            noAnswerMessageInChannelDomainService);

                        if (chatbot.NoAnswerMessageInChannels != null && !string.IsNullOrEmpty(channel))
                        {
                            chatbot.NoAnswerMessageInChannels = chatbot.NoAnswerMessageInChannels.Where(f => f.Channel == channel).ToList();
                        }
                    }

                    if (!string.IsNullOrEmpty(include) 
                        && include.Equals("messageAfterSeveralConsecutivePossibleAnswersInChannels"))
                    {
                        LoadMessageAfterSeveralConsecutivePossibleAnswersInChannel(chatbot,
                            messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService);

                        if (chatbot.MessageAfterSeveralConsecutivePossibleAnswersInChannels != null && !string.IsNullOrEmpty(channel))
                        {
                            chatbot.MessageAfterSeveralConsecutivePossibleAnswersInChannels = chatbot.MessageAfterSeveralConsecutivePossibleAnswersInChannels.Where(f => f.Channel == channel).ToList();
                        }
                    }
                }
            }
            return _repository.ListAll();
        }

        public void Delete(Guid id)
        {
            var chatbot = _repository.Get(id);

            ICategoryDomainService categoryDomainService = _container.Resolve<ICategoryDomainService>();
            IEntityDomainService entityDomainService = _container.Resolve<IEntityDomainService>();
            IQuickReplyDomainService quickReplyDomainService = _container.Resolve<IQuickReplyDomainService>();
            IGreetingMessageInChannelDomainService greetingMessageInChannelDomainService = _container.Resolve<IGreetingMessageInChannelDomainService>();
            INoAnswerMessageInChannelDomainService noAnswerMessageInChannelDomainService = _container.Resolve<INoAnswerMessageInChannelDomainService>();
            IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService = _container.Resolve<IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService>();

            var greetingMessageInChannels = greetingMessageInChannelDomainService.GetByBotId(id);
            if (greetingMessageInChannels != null)
            {
                foreach(var greetingMessageInChannel in greetingMessageInChannels)
                {
                    greetingMessageInChannelDomainService.Delete(greetingMessageInChannel.Id);
                }
            }
            var noAnswerMessageInChannels = noAnswerMessageInChannelDomainService.GetByBotId(id);
            if (noAnswerMessageInChannels != null)
            {
                foreach (var noAnswerMessageInChannel in noAnswerMessageInChannels)
                {
                    noAnswerMessageInChannelDomainService.Delete(noAnswerMessageInChannel.Id);
                }
            }
            var messageAfterSeveralConsecutivePossibleAnswersInChannels = messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService.GetByBotId(id);
            if (messageAfterSeveralConsecutivePossibleAnswersInChannels != null)
            {
                foreach (var messageAfterSeveralConsecutivePossibleAnswersInChannel in messageAfterSeveralConsecutivePossibleAnswersInChannels)
                {
                    messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService.Delete(messageAfterSeveralConsecutivePossibleAnswersInChannel.Id);
                }
            }
            var categorys = categoryDomainService.GetByBotId(id);
            if (categorys != null)
            {
                foreach (var category in categorys)
                {
                    categoryDomainService.Delete(category.Id);
                }
            }
            var quickReplys = quickReplyDomainService.GetByBotId(id);
            if (quickReplys != null)
            {
                foreach (var quickReply in quickReplys)
                {
                    quickReplyDomainService.Delete(quickReply.Id);
                }
            }
            var entitys = entityDomainService.GetAllByBotId(id);
            if (entitys != null)
            {
                foreach(var entity in entitys)
                {
                    entityDomainService.Delete(entity.Id);
                }
            }

            _repository.Delete(chatbot);

        }

        public int GetBotCountForSite(int siteId)
        {
            var count = _repository.Count(new ChatbotFilterSpecification(siteId));
            return count;
        }
        public bool NameCheck(int siteId, string name)
        {
            var count = _repository.Count(new ChatbotFilterSpecification(siteId,name));
            return count == 0;
        }

        public Operation Import(Guid jobId, string filePath, Chatbot bot)
        {
            throw new Exception();
        }

        public bool SetBotAsTrained(Guid id)
        {
            var bot = _repository.Get(id);
            bot.IsTrained = true;
            bot.LastUpdatedTime = DateTime.UtcNow;
            return true;
        }

        #region private

        private void LoadGreetingMessageInChannel(Chatbot chatbot,
            IGreetingMessageInChannelDomainService greetingMessageInChannelDomainService,
            string include)
        {
            var greetingMessageInChannels = greetingMessageInChannelDomainService.GetByBotId(chatbot.Id, include);
            chatbot.GreetingMessageInChannels = greetingMessageInChannels.ToList();
            //if (greetingMessageInChannels != null)
            //{
            //    var parentIds = greetingMessageInChannels.Select(a => a.Id).ToList();
            //    var responses = responseDomainService.GetByParentIds(parentIds);

            //    foreach (var greetingMessageInChannel in greetingMessageInChannels)
            //    {
            //        var channelResponses = responses.Where(f => f.ParentId == greetingMessageInChannel.Id);
            //        foreach (var response in channelResponses)
            //        {
            //            if (response.Type == Enum.EnumAnswerType.image && response.ImageId.HasValue)
            //            {
            //                var image = imageDomainService.Get(response.ImageId.Value);
            //                response.Image = image;
            //            }
            //            if (response.Type == Enum.EnumAnswerType.quickReply && response.QuickReplyId.HasValue)
            //            {
            //                var quickReply = quickReplyRepository.Get(response.QuickReplyId.Value);
            //                if (quickReply != null)
            //                {
            //                    var quickReplyItems = quickReplyItemRepository.List(new QuickReplyItemFilterSpecification(quickReply.Id));
            //                    quickReply.Items = quickReplyItems.ToList();
            //                }
            //                response.QuickReply = quickReply;
            //            }
            //            if (response.Type == Enum.EnumAnswerType.button)
            //            {
            //                var responseButtons = responseButtonRepository.List(new ResponseButtonFilterSpecification(response.Id));
            //                foreach (var responseButton in responseButtons)
            //                {
            //                    if (responseButton.Type == Enum.EnumButtonType.goToIntent && responseButton.IntentId.HasValue)
            //                    {
            //                        var intent = intentRepository.Get(responseButton.IntentId.Value);
            //                        responseButton.Intent = intent;
            //                    }
            //                }
            //                response.Buttons = responseButtons.ToList();
            //            }
            //            if (response.Type == Enum.EnumAnswerType.webhook && response.WebhookId.HasValue)
            //            {
            //                var webhook = webhookRepository.Get(response.WebhookId.Value);
            //                response.Webhook = webhook;
            //            }
            //        }
            //    }

            //    chatbot.GreetingMessageInChannels = greetingMessageInChannels.ToList();
            //}
        }
        private void LoadNoAnswerMessageInChannel(Chatbot chatbot,
            INoAnswerMessageInChannelDomainService noAnswerMessageInChannelDomainService)
        {            
            var noAnswerMessageInChannels = noAnswerMessageInChannelDomainService.GetByBotId(chatbot.Id);
            chatbot.NoAnswerMessageInChannels = noAnswerMessageInChannels.ToList();
        }
        private void LoadMessageAfterSeveralConsecutivePossibleAnswersInChannel(Chatbot chatbot,
            IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService)
        {            
            var messageAfterSeveralConsecutivePossibleAnswersInChannels = messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService.GetByBotId(chatbot.Id);
            chatbot.MessageAfterSeveralConsecutivePossibleAnswersInChannels = messageAfterSeveralConsecutivePossibleAnswersInChannels.ToList();
        }

        public static BotDto GetDefaultBotSettings(string languageCode)
        {

            switch (languageCode)
            {
                case "zh-cn":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "你好，我是聊天机器人。请问有什么我能帮你的吗？" } } } } } },
                        NoResponseMessage = "你好，我还在学习中，现在还不能回答你的问题。请点击下方的按钮联系人工客服。",
                        IsShowAgentLinkWhenNoResponse = true,
                        NotHelpfulMessage = "很抱歉我的回复没能回答你的问题。请点击下方的按钮联系人工客服。",
                        IsShowAgentLinkWhenNotHelpful = true,
                        PossibleResponsesMessage = "我找到了一个相关问题或许能帮助到你。你的问题和以下某个问题类似吗？",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "看来这些链接都不能回答你的问题。请点击下方的按钮联系人工客服。",
                        TextWhenAgentIsOnline = "转人工服务",
                        TextWhenAgentIsOffline = "给客服留言",
                        TransferAgentMessage = "我们正在帮您连接人工客服",
                        LeaveAMessageClickedMessage = "您可以在这里留言，我们随后会检查的。请注意，在这个阶段，您连接不到Bot。",
                        RequestVisitorLocationMessage = "请分享您的位置",
                        LocationButtonText = "发送位置",
                        SubmitButtonText = "提交",
                        CancelButtonText = "取消",
                        ConfirmButtonText = "确认",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "你好，我还在学习中，现在还不能回答你的问题。请点击下方的按钮联系人工客服。", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "看来这些链接都不能回答你的问题。请点击下方的按钮联系人工客服。", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "zh-hk":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "你好，我系倾计机器人。请问有咩我可唔可以帮到你嘅？" } } } } } },
                        NoResponseMessage = "你好，我仲喺度学习紧，而家仲答唔到你嘅问题。唔该点击下方嘅链接联系人工客服",
                        IsShowAgentLinkWhenNoResponse = true,
                        NotHelpfulMessage = "对唔住，我嘅回复答唔到你嘅问题。唔该点击下方嘅链接联系人工客服。",
                        IsShowAgentLinkWhenNotHelpful = true,
                        PossibleResponsesMessage = "我揾到一啲有关问题或者可以帮到你，你嘅问题同以下某个问题类似吗？",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "睇嚟呢啲链接都答唔到你嘅问题，唔该点击下方嘅链接联系人工客服。",
                        TextWhenAgentIsOnline = "转人工服务",
                        TextWhenAgentIsOffline = "给客服留言",
                        TransferAgentMessage = "我哋喺度帮你链接人工客服",
                        LeaveAMessageClickedMessage = "你可以喺呢度留言，我哋随后会检查。唔该注意，喺呢个阶段，你链接唔到Bot。",
                        RequestVisitorLocationMessage = "唔该分享你个位",
                        LocationButtonText = "发送位置",
                        SubmitButtonText = "提交",
                        CancelButtonText = "取消",
                        ConfirmButtonText = "确认",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "你好，我仲喺度学习紧，而家仲答唔到你嘅问题。唔该点击下方嘅链接联系人工客服", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "睇嚟呢啲链接都答唔到你嘅问题，唔该点击下方嘅链接联系人工客服。", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "zh-tw":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "你好，我是聊天機器人。請問有什麼我能幫你的嗎？" } } } } } },
                        NoResponseMessage = "你好，我還在學習中，現在還不能回答你的問題。請點擊下方的按鈕聯繫人工客服。",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "很抱歉我的回复沒能回答你的問題。請點擊下方的按鈕聯繫人工客服。",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "我找到了一个相關問題或許能幫助到你。你的問題和以下某個問題類似嗎？",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "聯繫人工客服。",
                        TextWhenAgentIsOnline = "轉人工服務",
                        TextWhenAgentIsOffline = "給客服留言",
                        TransferAgentMessage = "我們正在幫您連接人工客服",
                        LeaveAMessageClickedMessage = "您可以在這裡留言，我們隨後會檢查的。請注意，在這個階段，您連接不到Bot。",
                        RequestVisitorLocationMessage = "請分享您的位置",
                        LocationButtonText = "发送位置",
                        SubmitButtonText = "提交",
                        CancelButtonText = "取消",
                        ConfirmButtonText = "確認",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "你好，我還在學習中，現在還不能回答你的問題。請點擊下方的按鈕聯繫人工客服。", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "聯繫人工客服。", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "fr":
                case "fr-ca":
                case "fr-fr":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Bonjour, je suis un robot de chat. Y a-t-il quelque chose que je puisse faire pour vous?" } } } } } },
                        NoResponseMessage = "Bonjour, j'apprends encore, je ne peux pas encore répondre à vos questions. Veuillez cliquer sur le bouton ci-dessous pour contacter le service client.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Je suis désolé que ma réponse n'ait pas répondu à votre question. Veuillez cliquer sur le bouton ci-dessous pour contacter le service client.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "J'ai trouvé des problèmes connexes qui pourraient vous aider. Votre question est-elle similaire à l'une des questions suivantes?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Il semble qu'aucun de ces liens ne peut répondre à votre question. Veuillez cliquer sur le bouton ci-dessous pour contacter le service client.",
                        TextWhenAgentIsOnline = "Transfert du service client artificiel",
                        TextWhenAgentIsOffline = "Laissez un message pour le service client",
                        TransferAgentMessage = "Nous vous connectons à un agent humain.",
                        LeaveAMessageClickedMessage = "vous pouvez laisser votre message ici pour que nous le vérifions plus tard, veuillez noter que vous ne pouvez pas vous reconnecter à bot à ce stade",
                        RequestVisitorLocationMessage = "Veuillez partager votre emplacement",
                        LocationButtonText = "Envoyer Emplacement",
                        SubmitButtonText = "Soumettre",
                        CancelButtonText = "Annuler",
                        ConfirmButtonText = "Confirmer",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Bonjour, j'apprends encore, je ne peux pas encore répondre à vos questions. Veuillez cliquer sur le bouton ci-dessous pour contacter le service client.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Il semble qu'aucun de ces liens ne peut répondre à votre question. Veuillez cliquer sur le bouton ci-dessous pour contacter le service client.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "da":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Hej der, dette er Chatbot. Hvordan kan jeg hjælpe dig i dag?" } } } } } },
                        NoResponseMessage = "Hej, jeg lærer stadig. Jeg er bange for, at jeg ikke kan hjælpe dig med dette. Klik på den følgende knap for at oprette forbindelse til en agent.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Jeg beklager, at dette ikke svarer på dit spørgsmål. Klik på den følgende knap for at oprette forbindelse til en agent.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "Jeg har nogle relevante spørgsmål, der kan hjælpe dig. Er dit spørgsmål lignet et af nedenstående spørgsmål?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Det ser ud til, at ingen af disse links besvarer dit spørgsmål. Klik på den følgende knap for at oprette forbindelse til en agent.",
                        TextWhenAgentIsOnline = "Chat med Human Agent",
                        TextWhenAgentIsOffline = "Læg en besked",
                        TransferAgentMessage = "Vi forbinder dig med en human agent.",
                        LeaveAMessageClickedMessage = "du kan efterlade din besked her for at kontrollere senere at bemærke, at du ikke kan genoprette forbindelse til bot på dette tidspunkt.",
                        RequestVisitorLocationMessage = "Venligst del din placering",
                        LocationButtonText = "Send Sted",
                        SubmitButtonText = "Indsend",
                        CancelButtonText = "Afbestille",
                        ConfirmButtonText = "Bekræfte",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Hej, jeg lærer stadig. Jeg er bange for, at jeg ikke kan hjælpe dig med dette. Klik på den følgende knap for at oprette forbindelse til en agent.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Det ser ud til, at ingen af disse links besvarer dit spørgsmål. Klik på den følgende knap for at oprette forbindelse til en agent.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "it":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Salve, questo è Chatbot. Come posso aiutarti oggi?" } } } } } },
                        NoResponseMessage = "Ciao, sto ancora imparando. Ho paura di non poterti aiutare con questo. Fare clic sul seguente pulsante per connettersi a un agente.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Mi dispiace che questo non risponda alla tua domanda. Fare clic sul seguente pulsante per connettersi a un agente.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "Ti ho fatto alcune domande pertinenti che potrebbero aiutarti. La tua domanda è simile a una delle domande seguenti?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Sembra che nessuno di questi link risponda alla tua domanda. Fare clic sul seguente pulsante per connettersi a un agente.",
                        TextWhenAgentIsOnline = "Chatta con l'agente umano",
                        TextWhenAgentIsOffline = "Lasciate un messaggio",
                        TransferAgentMessage = "Ti stiamo connettendo a un agente umano.",
                        LeaveAMessageClickedMessage = "puoi lasciare il tuo messaggio qui per noi per verificare in seguito gentilmente nota che non è possibile riconnettersi al bot in questa fase.",
                        RequestVisitorLocationMessage = "Si prega di condividere la tua posizione",
                        LocationButtonText = "Invia posizione",
                        SubmitButtonText = "Sottoscrivi",
                        CancelButtonText = "Annulla",
                        ConfirmButtonText = "Confermare",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Ciao, sto ancora imparando. Ho paura di non poterti aiutare con questo. Fare clic sul seguente pulsante per connettersi a un agente.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Sembra che nessuno di questi link risponda alla tua domanda. Fare clic sul seguente pulsante per connettersi a un agente.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "nl":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Hallo daar, dit is Chatbot. Hoe kan ik je vandaag helpen?" } } } } } },
                        NoResponseMessage = "Hallo, ik ben nog aan het leren. Ik ben bang dat ik je hiermee niet kan helpen. Klik op de knop Volgende om verbinding te maken met een agent.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Het spijt me dat dit uw vraag niet beantwoordt. Klik op de knop Volgende om verbinding te maken met een agent.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "Ik heb een aantal relevante vragen die kunnen helpen. Is uw vraag vergelijkbaar met een van de onderstaande vragen?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Het lijkt erop dat geen van deze links uw vraag beantwoordt. Klik op de knop Volgende om verbinding te maken met een agent.",
                        TextWhenAgentIsOnline = "Chat met Human Agent",
                        TextWhenAgentIsOffline = "Laat een bericht achter",
                        TransferAgentMessage = "We verbinden je met een menselijke agent.",
                        LeaveAMessageClickedMessage = "je kunt hier je bericht achterlaten om later te controleren dat je in dit stadium niet opnieuw kunt verbinden met bot.",
                        RequestVisitorLocationMessage = "Deel alstublieft uw locatie",
                        LocationButtonText = "Stuur Locatie",
                        SubmitButtonText = "Voorleggen",
                        CancelButtonText = "Annuleer",
                        ConfirmButtonText = "Bevestigen",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Hallo, ik ben nog aan het leren. Ik ben bang dat ik je hiermee niet kan helpen. Klik op de knop Volgende om verbinding te maken met een agent.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Het lijkt erop dat geen van deze links uw vraag beantwoordt. Klik op de knop Volgende om verbinding te maken met een agent.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "de":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Hallo, das ist Chatbot. Wie kann ich Ihnen heute helfen?" } } } } } },
                        NoResponseMessage = "Hi, ich lerne immer noch. Ich fürchte, ich kann dir damit nicht helfen. Bitte klicken Sie auf den folgenden Button, um sich mit einem Agenten zu verbinden.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Es tut mir leid, dass dies Ihre Frage nicht beantwortet. Bitte klicken Sie auf den folgenden Button, um sich mit einem Agenten zu verbinden.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "Ich habe einige relevante Fragen, die Ihnen helfen können. Ist Ihre Frage ähnlich wie bei einer der folgenden Fragen?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Es scheint, dass keiner dieser Links Ihre Frage beantwortet. Bitte klicken Sie auf den folgenden Button, um sich mit einem Agenten zu verbinden.",
                        TextWhenAgentIsOnline = "Chatte mit dem menschlichen Agenten",
                        TextWhenAgentIsOffline = "Hinterlass eine Nachricht",
                        TransferAgentMessage = "Wir verbinden dich mit einem menschlichen agenten.",
                        LeaveAMessageClickedMessage = "Sie können Ihre Nachricht hier hinterlassen, damit wir später überprüfen können, dass Sie zu diesem Zeitpunkt keine Verbindung zum Bot herstellen können.",
                        RequestVisitorLocationMessage = "Bitte teilen Sie Ihren Standort mit",
                        LocationButtonText = "Standort übermitteln",
                        SubmitButtonText = "Einreichen",
                        CancelButtonText = "Stornieren",
                        ConfirmButtonText = "Bestätigen",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Hi, ich lerne immer noch. Ich fürchte, ich kann dir damit nicht helfen. Bitte klicken Sie auf den folgenden Button, um sich mit einem Agenten zu verbinden.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Es scheint, dass keiner dieser Links Ihre Frage beantwortet. Bitte klicken Sie auf den folgenden Button, um sich mit einem Agenten zu verbinden.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "es":
                case "es-es":
                case "es-419":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Hola, este es Chatbot. ¿Como puedo ayudarte hoy?" } } } } } },
                        NoResponseMessage = "Hola, todavía estoy aprendiendo. Me temo que no puedo ayudarte con esto. Haga clic en el siguiente botón para conectarse a un agente.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Lamento que mi respuesta no haya respondido tu pregunta. Haga clic en el botón de abajo para contactar al servicio al cliente.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "Tengo algunas preguntas relevantes que pueden ser útiles. ¿Es su pregunta similar a cualquiera de las preguntas a continuación?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "parece que ninguno de estos enlaces responde su pregunta. por favor haga clic en el siguiente botón para conectarse a un agente.",
                        TextWhenAgentIsOnline = "Chatear con un agente humano",
                        TextWhenAgentIsOffline = "deja un mensaje",
                        TransferAgentMessage = "te estamos conectando a un agente humano.",
                        LeaveAMessageClickedMessage = "Puede dejar su mensaje aquí para que lo revisemos más tarde. Tenga en cuenta que no puede volver a conectarse a bot en esta etapa.",
                        RequestVisitorLocationMessage = "por favor comparta su ubicación",
                        LocationButtonText = "enviar ubicación",
                        SubmitButtonText = "enviar",
                        CancelButtonText = "cancelar",
                        ConfirmButtonText = "confirmar",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Hola, todavía estoy aprendiendo. Me temo que no puedo ayudarte con esto. Haga clic en el siguiente botón para conectarse a un agente.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "parece que ninguno de estos enlaces responde su pregunta. por favor haga clic en el siguiente botón para conectarse a un agente.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "pt":
                case "pt-br":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Olá, sou um robô de chat. Existe alguma coisa que eu possa fazer por você?" } } } } } },
                        NoResponseMessage = "Olá, ainda estou aprendendo, não posso responder às suas perguntas ainda. Por favor, clique no botão abaixo para entrar em contato com o atendimento ao cliente.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Lamentamos que a minha resposta não tenha respondido à sua pergunta. Por favor, clique no botão abaixo para entrar em contato com o atendimento ao cliente.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "Eu encontrei alguns problemas relacionados que podem ajudá-lo. A sua pergunta é semelhante a uma das seguintes perguntas?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Parece que nenhum desses links pode responder sua pergunta. Por favor, clique no botão abaixo para entrar em contato com o atendimento ao cliente.",
                        TextWhenAgentIsOnline = "Transferir atendimento ao cliente artificial",
                        TextWhenAgentIsOffline = "Deixe uma mensagem para atendimento ao cliente",
                        TransferAgentMessage = "estamos conectando você a um agente humano.",
                        LeaveAMessageClickedMessage = "você pode deixar sua mensagem aqui para nós verificarmos mais tarde, gentilmente, note que você não pode se reconectar ao bot nesta fase.",
                        RequestVisitorLocationMessage = "por favor, compartilhe sua localização",
                        LocationButtonText = "enviar localização",
                        SubmitButtonText = "enviar",
                        CancelButtonText = "cancelar",
                        ConfirmButtonText = "confirme",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Olá, ainda estou aprendendo, não posso responder às suas perguntas ainda. Por favor, clique no botão abaixo para entrar em contato com o atendimento ao cliente.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Parece que nenhum desses links pode responder sua pergunta. Por favor, clique no botão abaixo para entrar em contato com o atendimento ao cliente.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "ko":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "안녕하세요, 여기 Chatbot입니다. 오늘 제가 어떻게 도와 드릴까요?" } } } } } },
                        NoResponseMessage = "안녕하세요, 저는 여전히 배우고 있습니다. 나는이 일로 너를 도울 수 없다는 것을 두려워한다. 다음 버튼을 클릭하여 에이전트에 연결하십시오.",
                        IsShowAgentLinkWhenNoResponse = true
                                ,
                        NotHelpfulMessage = "귀하의 질문에 답변을 드리지 못해 죄송합니다. 다음 버튼을 클릭하여 에이전트에 연결하십시오.",
                        IsShowAgentLinkWhenNotHelpful = true
                                ,
                        PossibleResponsesMessage = "도움이 될만한 몇 가지 질문을 드리겠습니다. 귀하의 질문이 아래의 질문과 유사합니까?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "이 링크들 중 어느 것도 귀하의 질문에 대답하지 않는 것 같습니다. 다음 버튼을 클릭하여 에이전트에 연결하십시오.",
                        TextWhenAgentIsOnline = "휴먼 에이젼트와 대화",
                        TextWhenAgentIsOffline = "메시지 남기기",
                        TransferAgentMessage = "우리는 당신을 인간 대리인과 연결시키고 있습니다.",
                        LeaveAMessageClickedMessage = "나중에 우리가이 단계에서 봇에 다시 연결할 수 없다는 것을 확인하기 위해 메시지를 남겨주세요.",
                        RequestVisitorLocationMessage = "내 위치 공유하기",
                        LocationButtonText = "위치를 보낸다.",
                        SubmitButtonText = "제출하다",
                        CancelButtonText = "취소",
                        ConfirmButtonText = "확인하다",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "안녕하세요, 저는 여전히 배우고 있습니다. 나는이 일로 너를 도울 수 없다는 것을 두려워한다. 다음 버튼을 클릭하여 에이전트에 연결하십시오.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "이 링크들 중 어느 것도 귀하의 질문에 대답하지 않는 것 같습니다. 다음 버튼을 클릭하여 에이전트에 연결하십시오.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "ja":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "こんにちは、これはChatbotです。 今日はどのようにお手伝いしますか？" } } } } } },
                        NoResponseMessage = "こんにちは、私はまだ学んでいます。 私はあなたにこれを手伝うことができないのではないかと心配しています。 次のボタンをクリックしてエージェントに接続してください。",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "これがあなたの質問に答えないのは残念です。 次のボタンをクリックしてエージェントに接続してください。",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "あなたに役立つかもしれない関連する質問があります。 あなたの質問は以下の質問と似ていますか？",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "これらのリンクのどれもあなたの質問に答えてくれないようです。 次のボタンをクリックしてエージェントに接続してください。",
                        TextWhenAgentIsOnline = "人間エージェントとのチャット",
                        TextWhenAgentIsOffline = "伝言を残す",
                        TransferAgentMessage = "私たちはあなたを人間のエージェントに接続しています。",
                        LeaveAMessageClickedMessage = "この段階でボットに再接続できないことにご注意ください。",
                        RequestVisitorLocationMessage = "あなたの場所を共有してください",
                        LocationButtonText = "場所を送る",
                        SubmitButtonText = "提出する",
                        CancelButtonText = "キャンセル",
                        ConfirmButtonText = "確認する",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "こんにちは、私はまだ学んでいます。 私はあなたにこれを手伝うことができないのではないかと心配しています。 次のボタンをクリックしてエージェントに接続してください。", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "これらのリンクのどれもあなたの質問に答えてくれないようです。 次のボタンをクリックしてエージェントに接続してください。", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "hi":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "हाय वहाँ, यह Chatbot है। आज मैं आपकी कैसे मदद कर सकता हूँ?" } } } } } },
                        NoResponseMessage = "हाय, मैं अभी भी सीख रहा हूँ। मुझे डर है कि मैं इसके साथ आपकी मदद नहीं कर सकता। किसी एजेंट से कनेक्ट करने के लिए कृपया निम्न बटन पर क्लिक करें।",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "मुझे खेद है कि यह आपके प्रश्न का उत्तर नहीं देता है। किसी एजेंट से कनेक्ट करने के लिए कृपया निम्न बटन पर क्लिक करें।",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "मुझे आपके पास कुछ प्रासंगिक प्रश्न हैं जो मदद कर सकते हैं। क्या आपका प्रश्न नीचे दिए गए किसी भी प्रश्न के समान है?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "ऐसा लगता है कि इनमें से कोई भी लिंक आपके प्रश्न का उत्तर नहीं देता है। किसी एजेंट से कनेक्ट करने के लिए कृपया निम्न बटन पर क्लिक करें।",
                        TextWhenAgentIsOnline = "मानव एजेंट के साथ चैट करें",
                        TextWhenAgentIsOffline = "एक संदेश छोड़ें",
                        TransferAgentMessage = "हम आपको मानव एजेंट से जोड़ रहे हैं।",
                        LeaveAMessageClickedMessage = "आप यहां हमारे संदेश को बाद में कृपया जांचने के लिए छोड़ सकते हैं कि आप इस चरण में बॉट से फिर से कनेक्ट नहीं हो सकते हैं।",
                        RequestVisitorLocationMessage = "कृपया अपना स्थान साझा करें",
                        LocationButtonText = "स्थान भेजें",
                        SubmitButtonText = "जमा करें",
                        CancelButtonText = "रद्द करना",
                        ConfirmButtonText = "की पुष्टि करें",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "हाय, मैं अभी भी सीख रहा हूँ। मुझे डर है कि मैं इसके साथ आपकी मदद नहीं कर सकता। किसी एजेंट से कनेक्ट करने के लिए कृपया निम्न बटन पर क्लिक करें।", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "ऐसा लगता है कि इनमें से कोई भी लिंक आपके प्रश्न का उत्तर नहीं देता है। किसी एजेंट से कनेक्ट करने के लिए कृपया निम्न बटन पर क्लिक करें।", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "id":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Halo, ini Chatbot. bagaimana saya bisa membantu Anda hari ini?" } } } } } },
                        NoResponseMessage = "Hai, saya masih belajar. Saya takut bahwa saya tidak dapat membantu Anda dengan ini. Silakan klik pada tombol berikut untuk terhubung ke agen.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Saya menyesal bahwa ini tidak menjawab pertanyaan Anda. Silakan klik pada tombol berikut untuk terhubung ke agen.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "Saya punya beberapa pertanyaan relevan yang dapat membantu Anda. Apakah pertanyaan Anda mirip dengan salah satu pertanyaan di bawah ini?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Tampaknya tidak ada tautan ini yang menjawab pertanyaan Anda. Silakan klik pada tombol berikut untuk terhubung ke agen.",
                        TextWhenAgentIsOnline = "Mengobrol dengan Agen Manusia",
                        TextWhenAgentIsOffline = "Tinggalkan pesan",
                        TransferAgentMessage = "kami menghubungkan Anda ke agen manusia.",
                        LeaveAMessageClickedMessage = "Anda dapat meninggalkan pesan Anda di sini untuk kami periksa nanti dengan catatan bahwa Anda tidak dapat terhubung kembali ke bot pada tahap ini.",
                        RequestVisitorLocationMessage = "tolong bagikan lokasi Anda",
                        LocationButtonText = "Kirim lokasi",
                        SubmitButtonText = "menyerahkan",
                        CancelButtonText = "membatalkan",
                        ConfirmButtonText = "memastikan",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Hai, saya masih belajar. Saya takut bahwa saya tidak dapat membantu Anda dengan ini. Silakan klik pada tombol berikut untuk terhubung ke agen.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Tampaknya tidak ada tautan ini yang menjawab pertanyaan Anda. Silakan klik pada tombol berikut untuk terhubung ke agen.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "no":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Hei, dette er Chatbot. Hvordan kan jeg hjelpe deg i dag?" } } } } } },
                        NoResponseMessage = "Hei, jeg lærer fortsatt. Jeg er redd for at jeg ikke kan hjelpe deg med dette. Vennligst klikk på følgende knapp for å koble til en agent.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Jeg beklager at dette ikke svarer på spørsmålet ditt. Vennligst klikk på følgende knapp for å koble til en agent.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "Jeg har noen relevante spørsmål som kan hjelpe deg. Er spørsmålet ditt likt et av spørsmålene nedenfor?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Det ser ut til at ingen av disse koblingene svarer på spørsmålet ditt. Vennligst klikk på følgende knapp for å koble til en agent.",
                        TextWhenAgentIsOnline = "Chat med Human Agent",
                        TextWhenAgentIsOffline = "Legg igjen en beskjed",
                        TransferAgentMessage = "Vi forbinder deg med en menneskelig agent.",
                        LeaveAMessageClickedMessage = "Du kan legge meldingen din her for å sjekke senere, vennligst merk at du ikke kan koble til bot på dette stadiet.",
                        RequestVisitorLocationMessage = "vennligst del din plassering",
                        LocationButtonText = "send plassering",
                        SubmitButtonText = "sende inn",
                        CancelButtonText = "Avbryt",
                        ConfirmButtonText = "bekrefte",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Hei, jeg lærer fortsatt. Jeg er redd for at jeg ikke kan hjelpe deg med dette. Vennligst klikk på følgende knapp for å koble til en agent.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Det ser ut til at ingen av disse koblingene svarer på spørsmålet ditt. Vennligst klikk på følgende knapp for å koble til en agent.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "ru":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Привет, это Чатбот. Чем я вам сегодня могу помочь?" } } } } } },
                        NoResponseMessage = "Привет, я все еще учусь. Боюсь, что я не могу с этим поделать. Нажмите на следующую кнопку, чтобы подключиться к агенту.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Мне жаль, что это не отвечает на ваш вопрос. Нажмите на следующую кнопку, чтобы подключиться к агенту.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "У меня есть некоторые актуальные вопросы, которые могут помочь. Ваш вопрос аналогичен любому из вопросов ниже?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Кажется, что ни одна из этих ссылок не отвечает на ваш вопрос. Нажмите на следующую кнопку, чтобы подключиться к агенту.",
                        TextWhenAgentIsOnline = "Чат с человеческим агентом",
                        TextWhenAgentIsOffline = "Оставить сообщение",
                        TransferAgentMessage = "мы связываем вас с человеческим агентом.",
                        LeaveAMessageClickedMessage = "вы можете оставить свое сообщение здесь, чтобы мы могли позже проверить, что вы не можете повторно подключиться к боту на этом этапе.",
                        RequestVisitorLocationMessage = "пожалуйста, поделитесь своим местоположением",
                        LocationButtonText = "отправить местоположение",
                        SubmitButtonText = "Отправить",
                        CancelButtonText = "Отмена",
                        ConfirmButtonText = "подтвердить",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Привет, я все еще учусь. Боюсь, что я не могу с этим поделать. Нажмите на следующую кнопку, чтобы подключиться к агенту.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Кажется, что ни одна из этих ссылок не отвечает на ваш вопрос. Нажмите на следующую кнопку, чтобы подключиться к агенту.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "sv":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Hej där, det här är Chatbot. Hur kan jag hjälpa dig idag?" } } } } } },
                        NoResponseMessage = "Hej, jag lär mig fortfarande. Jag är rädd att jag inte kan hjälpa dig med det här. Vänligen klicka på följande knapp för att ansluta till en agent.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Jag beklagar att det här inte svarar på din fråga. Vänligen klicka på följande knapp för att ansluta till en agent.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "Jag har några relevanta frågor som kan hjälpa till. Är din fråga liknande någon av frågorna nedan?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "It seems that none of these links answers your question. Please click on following button to connect to an agent.",
                        TextWhenAgentIsOnline = "Chatta med Human Agent",
                        TextWhenAgentIsOffline = "Lämna ett meddelande",
                        TransferAgentMessage = "Vi ansluter dig till en human agent.",
                        LeaveAMessageClickedMessage = "du kan lämna ditt meddelande här för att vi ska kolla senare, vänligen notera att du inte kan ansluta till bot på det här steget.",
                        RequestVisitorLocationMessage = "snälla dela din plats",
                        LocationButtonText = "skicka plats",
                        SubmitButtonText = "lämna",
                        CancelButtonText = "annullera",
                        ConfirmButtonText = "bekräfta",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Hej, jag lär mig fortfarande. Jag är rädd att jag inte kan hjälpa dig med det här. Vänligen klicka på följande knapp för att ansluta till en agent.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "It seems that none of these links answers your question. Please click on following button to connect to an agent.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "th":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "สวัสดีที่นี่ Chatbot วันนี้ฉันจะช่วยคุณได้อย่างไร?" } } } } } },
                        NoResponseMessage = "สวัสดีฉันยังเรียนอยู่ ฉันกลัวว่าฉันจะช่วยคุณไม่ได้ โปรดคลิกที่ปุ่มต่อไปนี้เพื่อเชื่อมต่อกับตัวแทน",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "ฉันเสียใจที่ไม่ได้ตอบคำถามของคุณ โปรดคลิกที่ปุ่มต่อไปนี้เพื่อเชื่อมต่อกับตัวแทน",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "ฉันมีคำถามที่เกี่ยวข้องกับคุณซึ่งอาจช่วยได้ คำถามของคุณคล้ายกับคำถามด้านล่างหรือไม่?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "ดูเหมือนว่าไม่มีการเชื่อมโยงเหล่านี้ตอบคำถามของคุณ โปรดคลิกที่ปุ่มต่อไปนี้เพื่อเชื่อมต่อกับตัวแทน",
                        TextWhenAgentIsOnline = "สนทนากับตัวแทนมนุษย์",
                        TextWhenAgentIsOffline = "ฝากข้อความ",
                        TransferAgentMessage = "เรากำลังเชื่อมต่อคุณกับตัวแทนของมนุษย์",
                        LeaveAMessageClickedMessage = "คุณอาจฝากข้อความไว้ที่นี่เพื่อให้เราสามารถตรวจสอบได้ในภายหลังว่าคุณไม่สามารถเชื่อมต่อกับบอทได้ในขั้นตอนนี้",
                        RequestVisitorLocationMessage = "โปรดแชร์ตำแหน่งของคุณ",
                        LocationButtonText = "ส่งตำแหน่ง",
                        SubmitButtonText = "เสนอ",
                        CancelButtonText = "ยกเลิก",
                        ConfirmButtonText = "ยืนยัน",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "สวัสดีฉันยังเรียนอยู่ ฉันกลัวว่าฉันจะช่วยคุณไม่ได้ โปรดคลิกที่ปุ่มต่อไปนี้เพื่อเชื่อมต่อกับตัวแทน", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "ดูเหมือนว่าไม่มีการเชื่อมโยงเหล่านี้ตอบคำถามของคุณ โปรดคลิกที่ปุ่มต่อไปนี้เพื่อเชื่อมต่อกับตัวแทน", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "uk":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Привіт там, це Chatbot. Як я можу допомогти вам сьогодні?" } } } } } },
                        NoResponseMessage = "Привіт, я все ще вчуся. Я боюсь, що я не можу вам допомогти з цим. Будь ласка, натисніть на кнопку нижче, щоб підключитися до агента.",
                        IsShowAgentLinkWhenNoResponse = true
            ,
                        NotHelpfulMessage = "Мені шкода, що це не відповідає на ваше запитання. Будь ласка, натисніть на кнопку нижче, щоб підключитися до агента.",
                        IsShowAgentLinkWhenNotHelpful = true
            ,
                        PossibleResponsesMessage = "У мене є кілька відповідних питань, які можуть допомогти. Чи є ваше запитання подібним до будь-якого з наведених нижче питань?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Здається, що жоден з цих посилань не відповідає на ваше запитання. Будь ласка, натисніть на кнопку нижче, щоб підключитися до агента.",
                        TextWhenAgentIsOnline = "Поговорити з людським агентом",
                        TextWhenAgentIsOffline = "Залишити повідомлення",
                        TransferAgentMessage = "ми під'єднуємо вас до людського агента.",
                        LeaveAMessageClickedMessage = "ви можете залишити ваше повідомлення тут, щоб ми могли пізніше перевірити, будь ласка, зауважте, що на даному етапі ви не можете повернутися до бота.",
                        RequestVisitorLocationMessage = "будь ласка, поділіться своїм місцезнаходженням",
                        LocationButtonText = "відправити місцезнаходження",
                        SubmitButtonText = "подати",
                        CancelButtonText = "скасувати",
                        ConfirmButtonText = "підтвердити",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Привіт, я все ще вчуся. Я боюсь, що я не можу вам допомогти з цим. Будь ласка, натисніть на кнопку нижче, щоб підключитися до агента.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Здається, що жоден з цих посилань не відповідає на ваше запитання. Будь ласка, натисніть на кнопку нижче, щоб підключитися до агента.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "pl":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Cześć, tu Chatbot. Jak mogę Ci dziś pomóc?" } } } } } },
                        NoResponseMessage = "Cześć, wciąż się uczę. Obawiam się, że nie mogę ci w tym pomóc. Kliknij poniższy przycisk, aby połączyć się z agentem.",
                        IsShowAgentLinkWhenNoResponse = true,
                        NotHelpfulMessage = "Przykro mi, że to nie odpowiada na twoje pytanie. Kliknij poniższy przycisk, aby połączyć się z agentem.",
                        IsShowAgentLinkWhenNotHelpful = true,
                        PossibleResponsesMessage = "Mam dla ciebie odpowiednie pytanie, które może pomóc. Czy twoje pytanie jest podobne do któregokolwiek z poniższych pytań?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Wydaje się, że żaden z tych linków nie odpowiada na twoje pytanie. Kliknij poniższy przycisk, aby połączyć się z agentem.",
                        TextWhenAgentIsOnline = "Czatuj z Human Agent",
                        TextWhenAgentIsOffline = "Zostaw wiadomość",
                        TransferAgentMessage = "Łączymy cię z agentem ludzkim.",
                        LeaveAMessageClickedMessage = "Możesz zostawić wiadomość tutaj, abyśmy mogli sprawdzić później. Prosimy pamiętać, że na tym etapie nie można ponownie połączyć się z botem.",
                        RequestVisitorLocationMessage = "Udostępnij swoją lokalizację",
                        LocationButtonText = "Wyślij lokalizację",
                        SubmitButtonText = "Zatwierdź",
                        CancelButtonText = "Anuluj",
                        ConfirmButtonText = "Potwierdzać",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Cześć, wciąż się uczę. Obawiam się, że nie mogę ci w tym pomóc. Kliknij poniższy przycisk, aby połączyć się z agentem.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Wydaje się, że żaden z tych linków nie odpowiada na twoje pytanie. Kliknij poniższy przycisk, aby połączyć się z agentem.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                case "tr":
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Merhaba, burası Chatbot. Bugün size nasıl yardımcı olabilirim?" } } } } } },
                        NoResponseMessage = "Merhaba, ben hala öğreniyorum. Korkarım sana bu konuda yardımcı olamam. Bir acenteye bağlanmak için lütfen aşağıdaki butona tıklayın.",
                        IsShowAgentLinkWhenNoResponse = true,
                        NotHelpfulMessage = "Sorunun cevabını bulamadığı için üzgünüm. Bir acenteye bağlanmak için lütfen aşağıdaki butona tıklayın.",
                        IsShowAgentLinkWhenNotHelpful = true,
                        PossibleResponsesMessage = "Size yardımcı olabilecek bir sorum var. Sorunuz aşağıdaki sorulardan herhangi birine benzer mi?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "Bu bağlantıların hiçbiri sorunuzu cevaplamıyor gibi görünüyor. Bir acenteye bağlanmak için lütfen aşağıdaki butona tıklayın.",
                        TextWhenAgentIsOnline = "Human Agent ile sohbet et",
                        TextWhenAgentIsOffline = "Mesaj bırakın",
                        TransferAgentMessage = "Seni bir insan ajanına bağlıyoruz.",
                        LeaveAMessageClickedMessage = "Mesajınızı daha sonra kontrol etmemiz için burada bırakabilirsiniz. Lütfen bu aşamada bot ile tekrar bağlantı kuramayacağınızı unutmayın.",
                        RequestVisitorLocationMessage = "Lütfen konumunuzu paylaşın",
                        LocationButtonText = "Konum göndermek",
                        SubmitButtonText = "Gönder",
                        CancelButtonText = "İptal etmek",
                        ConfirmButtonText = "Onaylamak",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Merhaba, ben hala öğreniyorum. Korkarım sana bu konuda yardımcı olamam. Bir acenteye bağlanmak için lütfen aşağıdaki butona tıklayın.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "Bu bağlantıların hiçbiri sorunuzu cevaplamıyor gibi görünüyor. Bir acenteye bağlanmak için lütfen aşağıdaki butona tıklayın.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
                default:
                    return new BotDto
                    {
                        GreetingMessage = new Dictionary<string, List<IntentResponsesDto>>() { { "default", new List<IntentResponsesDto> { new IntentResponsesDto { Type = EnumAnswerType.text, Content = new IntentTextResponsesDto { Texts = new List<string> { "Hi there! I'm a chatbot, here to help answer your questions." } } } } } },
                        NoResponseMessage = "I'm still learning how to answer that! In the meantime, one of my human friends can help answer your question.",
                        IsShowAgentLinkWhenNoResponse = true,
                        NotHelpfulMessage = "I'm sorry to hear that wasn't helpful 😞. If you'd like, I can connect you to a human for assistance.",
                        IsShowAgentLinkWhenNotHelpful = true,
                        PossibleResponsesMessage = "Hmm... Do any of these topics match what you're looking for?",
                        PossibleResponsesThreshold = 3,
                        IsShowAgentLinkWhenPossibleResponsesThreshold = true,
                        PossibleResponsesExceedThresholdMessage = "It seems like you're asking a question that I haven't been trained to answer yet. If you'd like, one of my human friends can answer that for you.",
                        TextWhenAgentIsOnline = "Chat with Human Agent",
                        TextWhenAgentIsOffline = "Leave a Message",
                        TransferAgentMessage = "We are connecting you to a human agent.",
                        LeaveAMessageClickedMessage = "OK – I'll hand you over to a human now. Just leave a message, and an agent will get back to you.",
                        RequestVisitorLocationMessage = "Please share your location",
                        LocationButtonText = "Send Location",
                        SubmitButtonText = "Submit",
                        CancelButtonText = "Cancel",
                        ConfirmButtonText = "Confirm",
                        NoAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "I'm still learning how to answer that! In the meantime, one of my human friends can help answer your question.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                        PossibleAnswerMessage = new Dictionary<string, UnrecognizedMessage> { { "default", new UnrecognizedMessage { Message = "It seems like you're asking a question that I haven't been trained to answer yet. If you'd like, one of my human friends can answer that for you.", IncludeContactAnAgentOption = true, IsEnabled = true } } },
                    };
            }
            //if (DefaultBotSettings != null && DefaultBotSettings.Count > 0)
            //return DefaultBotSettings.Where(m => m.LanguageCodes.Contains(languageCode.ToLower())).Select(m => m.DefaultSettings).FirstOrDefault();
            //return null;
        }
        private void AddGreetingMessage(Guid botId, ICollection<GreetingMessageInChannel> greetingMessageInChannels,
            IGreetingMessageInChannelDomainService greetingMessageInChannelDomainService)
        {
            if (greetingMessageInChannels != null)
            {
                var greetingMessageInChannelIds = new List<Guid> { };
                foreach (var greetingMessageInChannel in greetingMessageInChannels)
                {
                    if (greetingMessageInChannel.Id != Guid.Empty)
                    {
                        //编辑
                        var greetingMessageInChannelUpdateBo = Mapper.Map<GreetingMessageInChannelUpdateBo>(greetingMessageInChannel);
                        greetingMessageInChannelDomainService.Update(greetingMessageInChannelUpdateBo);
                        greetingMessageInChannelIds.Add(greetingMessageInChannel.Id);
                    }
                    else
                    {
                        //新增
                        greetingMessageInChannel.Id = Guid.NewGuid();
                        greetingMessageInChannel.BotId = botId;
                        greetingMessageInChannelDomainService.Create(greetingMessageInChannel);
                        greetingMessageInChannelIds.Add(greetingMessageInChannel.Id);
                    }
                }

                //删除
                var greetingMessages = greetingMessageInChannelDomainService.GetByBotId(botId);
                foreach (var greetingMessageInChannel in greetingMessages)
                {
                    if (!greetingMessageInChannelIds.Contains(greetingMessageInChannel.Id))
                    {
                        greetingMessageInChannelDomainService.Delete(greetingMessageInChannel.Id);
                    }
                }
            }
        }
        private void AddUnrecognizedMessage(Guid botId,
             ICollection<NoAnswerMessageInChannel> noAnswerMessageInChannels,
             ICollection<MessageAfterSeveralConsecutivePossibleAnswersInChannel> messageAfterSeveralConsecutivePossibleAnswersInChannels,
             INoAnswerMessageInChannelDomainService noAnswerMessageInChannelDomainService,
             IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService)
        {
            List<Guid> noAnswerMessageInChannelIds = new List<Guid> { };
            if (noAnswerMessageInChannels != null)
            {
                foreach (var noAnswerMessageInChannel in noAnswerMessageInChannels)
                {
                    if (noAnswerMessageInChannel.Id != Guid.Empty)
                    {
                        //修改      
                        noAnswerMessageInChannel.BotId = botId;
                        var noAnswerMessageInChannelUpdateBo = Mapper.Map<NoAnswerMessageInChannelUpdateBo>(noAnswerMessageInChannel);
                        noAnswerMessageInChannelDomainService.Update(noAnswerMessageInChannelUpdateBo);
                        noAnswerMessageInChannelIds.Add(noAnswerMessageInChannel.Id);
                    }
                    else
                    {
                        //新增
                        noAnswerMessageInChannel.Id = Guid.NewGuid();
                        noAnswerMessageInChannel.BotId = botId;
                        noAnswerMessageInChannelDomainService.Create(noAnswerMessageInChannel);
                        noAnswerMessageInChannelIds.Add(noAnswerMessageInChannel.Id);
                    }
                }
            }
            //删除
            var noAnswerMessages = noAnswerMessageInChannelDomainService.GetByBotId(botId);
            foreach (var noAnswerMessageInChannel in noAnswerMessages)
            {
                if (!noAnswerMessageInChannelIds.Contains(noAnswerMessageInChannel.Id))
                {
                    noAnswerMessageInChannelDomainService.Delete(noAnswerMessageInChannel.Id);
                }
            }

            List<Guid> possibleAnswerMessageInChannelIds = new List<Guid> { };
            if (messageAfterSeveralConsecutivePossibleAnswersInChannels != null)
            {
                foreach (var messageAfterSeveralConsecutivePossibleAnswersInChannel in messageAfterSeveralConsecutivePossibleAnswersInChannels)
                {
                    if (messageAfterSeveralConsecutivePossibleAnswersInChannel.Id != Guid.Empty)
                    {
                        //修改
                        messageAfterSeveralConsecutivePossibleAnswersInChannel.BotId = botId;
                        var messageAfterSeveralConsecutivePossibleAnswersInChannelUpdateBo = Mapper.Map<MessageAfterSeveralConsecutivePossibleAnswersInChannelUpdateBo>(messageAfterSeveralConsecutivePossibleAnswersInChannel);
                        messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService.Update(messageAfterSeveralConsecutivePossibleAnswersInChannelUpdateBo);
                        possibleAnswerMessageInChannelIds.Add(messageAfterSeveralConsecutivePossibleAnswersInChannel.Id);
                    }
                    else
                    {
                        //新增
                        messageAfterSeveralConsecutivePossibleAnswersInChannel.Id = Guid.NewGuid();
                        messageAfterSeveralConsecutivePossibleAnswersInChannel.BotId = botId;
                        messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService.Create(messageAfterSeveralConsecutivePossibleAnswersInChannel);
                        possibleAnswerMessageInChannelIds.Add(messageAfterSeveralConsecutivePossibleAnswersInChannel.Id);
                    }
                }
            }
            //删除
            var possibleAnswerMessageInChannels = messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService.GetByBotId(botId);
            foreach (var possibleAnswerMessageInChannel in possibleAnswerMessageInChannels)
            {
                if (!possibleAnswerMessageInChannelIds.Contains(possibleAnswerMessageInChannel.Id))
                {
                    messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService.Delete(possibleAnswerMessageInChannel.Id);
                }
            }
        }
        private string CopyChitChatFile(int siteId, string cultrue)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UploadedFiles", siteId.ToString());
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string filePath = Path.Combine(path, string.Format("{0}.xlsx", Guid.NewGuid().ToString()));

            Assembly assembly = Assembly.GetExecutingAssembly();
            string projectName = assembly.GetName().Name;
            string resourceName = string.Format("{0}.App_Data.Chit_chat.{1}.xlsx", projectName, cultrue);
            var assemblyResources = assembly.GetManifestResourceNames();
            if (assemblyResources.Contains(resourceName))
            {
                using (Stream sm = assembly.GetManifestResourceStream(resourceName))
                {
                    int numBytesToRead = (int)sm.Length;
                    byte[] buffer = new byte[numBytesToRead];
                    sm.Read(buffer, 0, buffer.Length);
                    // 把 byte[] 写入文件   
                    using (FileStream fs = new FileStream(filePath, FileMode.Create))
                    {
                        using (BinaryWriter bw = new BinaryWriter(fs))
                        {
                            bw.Write(buffer);
                            //return fs.Name;
                        }
                    }
                }
            }
            else
            {
                filePath = "";
            }

            return filePath;
        }
        #endregion
//        #region 导入业务逻辑
//        public ImportResult ImportBotAsync(Guid jobId, string filePath, Chatbot bot)
//        {
//            string xmlFilePath = filePath;

//            EnumImportHandleStatus handleStatus = EnumImportHandleStatus.Busy;
//            IList<string> errorMessages = new List<string>();

//            BackgroundJob backgroundJob = null;
//            BotImportDataQueue botImportDataQueue = GetImportDataQueue(jobId, xmlFilePath, bot, out backgroundJob);
//            try
//            {
//                if (botImportDataQueue.ProcessState == EnumProcessState.Occupy)
//                {
//                    //线程处理中
//                    handleStatus = EnumImportHandleStatus.Busy;
//                }
//                else
//                {
//                    switch (botImportDataQueue.Status)
//                    {
//                        case EnumImportHandleStatus.Wait:
//                            {
//                                botImportDataQueue.ProcessId = 1;
//                                errorMessages = await CheckData(botImportDataQueue, bot);
//                                if (errorMessages != null && errorMessages.Count > 0)
//                                {
//                                    //存在错误
//                                    botImportDataQueue.Status = EnumImportHandleStatus.Failed;
//                                    botImportDataQueue.ErrorMessages = errorMessages;
//                                    botImportDataQueue.ErrorCode = 50227;
//                                    string message = APIWrapper.APIHelper.GetErrorMessageByCode(botImportDataQueue.ErrorCode)?.Message;
//                                    if (!string.IsNullOrEmpty(message))
//                                    {
//                                        message = string.Join(" ", errorMessages);
//                                        botImportDataQueue.ErrorMessages = new string[] { " " + message };
//                                    }
//                                }
//                                else
//                                {
//                                    botImportDataQueue.Status = EnumImportHandleStatus.CheckData;
//                                }
//                                break;
//                            }
//                        case EnumImportHandleStatus.CheckData:
//                            {
//                                botImportDataQueue.ProcessId = 2;
//                                string appId = botImportDataQueue.AppId;
//                                decimal versionId = botImportDataQueue.VersionId;
//                                string errorMessage = "";
//                                ApiResult apiResult = await _botApiService.RestoreBot(botImportDataQueue);

//                                if (!apiResult.IsSuccess)
//                                {
//                                    //存在错误
//                                    errorMessage = apiResult.Error.Message;
//                                    botImportDataQueue.Status = EnumImportHandleStatus.Failed;
//                                    errorMessages.Add(errorMessage);
//                                    botImportDataQueue.ErrorMessages = errorMessages;
//                                    botImportDataQueue.ErrorCode = 50228;
//                                }
//                                else
//                                {
//                                    if (apiResult.Data != null)
//                                    {
//                                        botImportDataQueue.Status = EnumImportHandleStatus.BotEngineImportProceeing;
//                                        botImportDataQueue.OperationName = apiResult.Data.ToString();
//                                    }
//                                    else
//                                    {
//                                        botImportDataQueue.Status = EnumImportHandleStatus.BotEngineImportCompleted;
//                                    }
//                                }
//                                break;
//                            }
//                        case EnumImportHandleStatus.BotEngineImportProceeing:
//                            {
//                                botImportDataQueue.ProcessId = 2;
//                                string appId = botImportDataQueue.AppId;
//                                decimal versionId = botImportDataQueue.VersionId;
//                                string errorMessage = "";

//                                int siteId = botImportDataQueue.SiteId;
//                                Guid botId = botImportDataQueue.BotId;
//                                string name = botImportDataQueue.OperationName;
//                                ApiResult apiResult = await _botApiService.GetOperations(siteId, botId, name);

//                                if (!apiResult.IsSuccess)
//                                {
//                                    //存在错误
//                                    errorMessage = apiResult.Error.Message;
//                                    botImportDataQueue.Status = EnumImportHandleStatus.Failed;
//                                    errorMessages.Add(apiResult.Error.Message);
//                                    botImportDataQueue.ErrorMessages = errorMessages;
//                                    botImportDataQueue.ErrorCode = 50229;
//                                }
//                                else
//                                {
//                                    if (apiResult.Data != null)
//                                    {
//                                        botImportDataQueue.Status = EnumImportHandleStatus.BotEngineImportProceeing;
//                                        botImportDataQueue.OperationName = apiResult.Data.ToString();
//                                    }
//                                    else
//                                    {
//                                        botImportDataQueue.Status = EnumImportHandleStatus.BotEngineImportCompleted;
//                                    }
//                                }

//                                break;
//                            }
//                        case EnumImportHandleStatus.BotEngineImportCompleted:
//                            {
//                                botImportDataQueue.ProcessId = 3;
//                                string errorMessage = await InitDataWithBotEngine(botImportDataQueue.BotImportData, bot);
//                                if (!string.IsNullOrEmpty(errorMessage))
//                                {
//                                    //存在错误
//                                    botImportDataQueue.Status = EnumImportHandleStatus.Failed;
//                                    errorMessages.Add(errorMessage);
//                                    botImportDataQueue.ErrorMessages = errorMessages;
//                                    botImportDataQueue.ErrorCode = 50230;
//                                }
//                                else
//                                {
//                                    botImportDataQueue.Status = EnumImportHandleStatus.InitDataWithBotEngine;
//                                }
//                                break;
//                            }
//                        case EnumImportHandleStatus.InitDataWithBotEngine:
//                            {
//                                botImportDataQueue.ProcessId = 4;
//                                //数据队列化 ,缓存到内存中
//                                string errorMessage = BotImportData2Queue(botImportDataQueue, botImportDataQueue.BotImportData);
//                                if (!string.IsNullOrEmpty(errorMessage))
//                                {
//                                    //存在错误
//                                    botImportDataQueue.Status = EnumImportHandleStatus.Failed;
//                                    errorMessages.Add(errorMessage);
//                                    botImportDataQueue.ErrorMessages = errorMessages;
//                                    botImportDataQueue.ErrorCode = 50231;
//                                }
//                                else
//                                {
//                                    botImportDataQueue.Status = EnumImportHandleStatus.ImportData2Queue;
//                                }
//                                break;
//                            }
//                        case EnumImportHandleStatus.ImportData2Queue:
//                            {
//                                botImportDataQueue.ProcessId = 5;
//                                //删除 Bot 相关数据
//                                string errorMessage = DeleteBotInfo(bot);
//                                if (!string.IsNullOrEmpty(errorMessage))
//                                {
//                                    //存在错误
//                                    botImportDataQueue.Status = EnumImportHandleStatus.Failed;
//                                    errorMessages.Add(errorMessage);
//                                    botImportDataQueue.ErrorMessages = errorMessages;
//                                    botImportDataQueue.ErrorCode = 50232;
//                                }
//                                else
//                                {
//                                    botImportDataQueue.Status = EnumImportHandleStatus.DeleteBotInfo;
//                                }

//                                break;
//                            }
//                        case EnumImportHandleStatus.DeleteBotInfo:
//                        case EnumImportHandleStatus.Processing:
//                            {
//                                botImportDataQueue.ProcessId = 6;
//                                string errorMessage = SaveDbForBotImportData(botImportDataQueue, bot);
//                                if (!string.IsNullOrEmpty(errorMessage))
//                                {
//                                    //存在错误
//                                    botImportDataQueue.Status = EnumImportHandleStatus.Failed;
//                                    errorMessages.Add(errorMessage);
//                                    botImportDataQueue.ErrorMessages = errorMessages;
//                                    botImportDataQueue.ErrorCode = 50233;
//                                }
//                                break;
//                            }
//                        case EnumImportHandleStatus.Publish:
//                            {
//                                botImportDataQueue.ProcessId = 7;
//                                string appId = botImportDataQueue.AppId;
//                                int siteId = botImportDataQueue.SiteId;
//                                decimal versionId = botImportDataQueue.VersionId;
//                                Guid botId = botImportDataQueue.BotId;
//                                string errorMessage = string.Empty;
//                                errorMessage = ReplaceIntentResponseText(siteId, bot.Id);
//                                //errorMessage = await PublishBot(appId, versionId, botId, luis);
//                                if (string.IsNullOrEmpty(errorMessage))
//                                {
//                                    botImportDataQueue.Status = EnumImportHandleStatus.Succeeded;
//                                }
//                                else
//                                {
//                                    botImportDataQueue.Status = EnumImportHandleStatus.Failed;
//                                    errorMessages.Add(errorMessage);
//                                    botImportDataQueue.ErrorMessages = errorMessages;
//                                    botImportDataQueue.ErrorCode = 50234;
//                                }
//                                break;
//                            }
//                        default:
//                            break;
//                    }

//                    handleStatus = botImportDataQueue.Status;
//                }
//            }
//            catch (Exception e)
//            {
//                errorMessages.Add(e.Message);
//                botImportDataQueue.ErrorMessages = errorMessages;
//                handleStatus = EnumImportHandleStatus.Failed;
//                LogHelper.Error(JsonConvert.SerializeObject(e));
//            }
//            finally
//            {
//                if (botImportDataQueue.ProcessState == EnumProcessState.Free)
//                {
//                    botImportDataQueue.ProcessState = EnumProcessState.Free;
//                    SetImportDataQueue(headGuid, filePath, botImportDataQueue, bot, backgroundJob);
//                }
//            }

//            if (handleStatus == EnumImportHandleStatus.Failed)
//            {//为了让下一次调用接口时候，返回上次的错误消息
//                errorMessages = botImportDataQueue.ErrorMessages;
//                //LogHelper.Error(JsonConvert.SerializeObject(new {
//                //    Processed = botImportDataQueue.ProcessId,
//                //    Status = handleStatus,
//                //    ErrorMessage = string.Join(",", errorMessages)
//                //}));
//            }

//            return new ImportResult
//            {
//                Processed = botImportDataQueue.ProcessId,
//                Total = 7,
//                Status = handleStatus,
//                ErrorMessage = string.Join(",", errorMessages),
//                OperationId = botImportDataQueue.OperationName,
//                ErrorCode = botImportDataQueue.ErrorCode,
//            };
//        }
//        private IList<string> CheckData(BotImportDataQueue botImportDataQueue, Chatbot bot)
//        {
//            IList<string> errorMessages = new List<string>();
//            string msg = CheckFile(botImportDataQueue.FileName);
//            if (!string.IsNullOrEmpty(msg))
//            {
//                errorMessages.Add(msg);
//                return errorMessages;
//            }

//            Dictionary<string, int> filedLenthDic = new Dictionary<string, int> {
//                { "Language", 24 },
//                { "BotName", 128 },
//                { "ChannelType", 20 },
//                { "Type", 20 },
//                { "Content", 8000 },
//                { "Text", 128 },
//                { "UrlOrIntentName", 1280 },
//                { "OpenIn", 20 },
//                { "OpenStyle", 20 },
//                { "NoResponseMessage", 1280 },
//                { "NotHelpfulMessage", 1280 },
//                { "PossibleResponsesMessage", 1280 },
//                { "PossibleResponsesExceedThresholdMessage", 1280 },
//                { "TextWhenAgentIsOnline", 1280 },
//                { "TextWhenAgentIsOffline", 1280 },
//                { "TransferAgentMessage", 1280 },
//                { "LeaveAMessageClickedMessage", 1280 },
//                { "RequestVisitorLocationMessage", 1280 },
//                { "LocationButtonText", 128 },
//                { "SubmitButtonText", 128 },
//                { "CancelButtonText", 128 },
//                { "ConfirmButtonText", 128 },
//                { "IntentName", 128 },
//                { "EntityCollectionType", 20 },
//                { "FormMessage", 1280 },
//                { "FormTitle", 1280 },
//                { "EntityLable", 128 },
//                { "SignInMessage", 1280 },
//                { "SignInLinkText", 128 },
//                { "SignInURL", 1280 },
//                { "CustomVariable", 128 },
//                { "FiledName", 128 },
//                { "Options", 1280 },
//                { "Questions", 4000 },
//                { "Answer", 8000 },
//                { "ButtonText", 128 },
//                { "EntityName", 128 },
//                { "DisplayName", 128 },
//                { "KeyWord", 128 },
//                { "SynonymsOfkeyWord", 4000 },
//                { "Name", 128 },
//                { "ConditionExpression", 2048 },
//                { "Variable", 128 },
//                { "Value", 2048 },
//                { "AgentOfflineMessage", 1280 },
//                { "Departments", 1280 },
//                { "Agents", 1280 },
//                { "ItemName", 1280 },
//            };

//            string xml = Utils.GetFileContent(botImportDataQueue.FileName);
//            string xsd = ReadResourceFile("BotImportDataSchema.xsd");
//            bool flag = Utils.XmlValidationByXsd(xml, xsd, filedLenthDic, out errorMessages);
//            //bool flag = true;
//            if (flag)
//            {
//                BotImportData botImportData = Utils.XmlDeserialize<BotImportData>(xml);
//                BotImportDataEx botImportDataEx = Mapper.Map<BotImportDataEx>(botImportData);
//                botImportDataQueue.BotImportData = botImportDataEx;

//                string[] enumChannelTypeArray = Enum.GetNames(typeof(Com.Comm100.Public.Enum.EnumChannelType)).Select(a => a.ToLower()).ToArray();

//                //从数据库查找bot信息
//                int siteId = bot.SiteId;
//                Guid botId = bot.Id;
//                string botName = bot.BotName;
//                string[] luisAppIds = bot.BotEngineAppId.Split(';');
//                string appId = luisAppIds.Last();
//                bool isSupportComplex = GetIsSupportComplex(siteId, botId);

//                if (string.IsNullOrEmpty(appId))
//                {
//                    throw new Exception("appid is empty");
//                }

//                //检测语言
//                if (!string.IsNullOrEmpty(botImportDataEx.Bot.Language))
//                {
//                    List<LanguageDto> languageDtos = _languageAppService.GetAll().Data as List<LanguageDto>;
//                    List<culture> ALLSupportedLanguages = AutoMapper.Mapper.Map<List<culture>>(languageDtos.Where(a => a.IfSupportedAiChatBot));

//                    if (!ALLSupportedLanguages.Exists(a => a.code == botImportDataEx.Bot.Language))
//                    {
//                        errorMessages.Add(string.Format("Language with code {0} is not supported.", botImportDataEx.Bot.Language));
//                    }
//                    if (botImportDataEx.Bot.Language.ToLower().Trim() != bot.Language.ToLower().Trim())
//                    {
//                        errorMessages.Add("Bot language cannot be modified.");
//                    }
//                }
//                else
//                {
//                    errorMessages.Add(string.Format("the language is required."));
//                }

//                //检测bot name 不能重复
//                if (!string.IsNullOrEmpty(botImportDataEx.Bot.BotName))
//                {
//                    if (!NameCheck(siteId, botId, botImportDataEx.Bot.BotName))
//                    {
//                        errorMessages.Add(string.Format("the bot name is exists."));
//                    }
//                }
//                else
//                {
//                    errorMessages.Add(string.Format("the bot name is required."));
//                }

//                //检测 HighConfidenceScore NoAnswerScore
//                if (botImportDataEx.Bot.HighConfidenceScore >= 1 && botImportDataEx.Bot.HighConfidenceScore <= 100)
//                {

//                }
//                else
//                {
//                    errorMessages.Add(string.Format("the HighConfidenceScore between 1 to 100."));
//                }

//                if (botImportDataEx.Bot.NoAnswerScore >= 0 && botImportDataEx.Bot.NoAnswerScore <= 100)
//                {

//                }
//                else
//                {
//                    errorMessages.Add(string.Format("the NoAnswerScore between 0 to 100."));
//                }

//                if (botImportDataEx.Bot.HighConfidenceScore > botImportDataEx.Bot.NoAnswerScore)
//                {

//                }
//                else
//                {
//                    errorMessages.Add(string.Format("the HighConfidenceScore must greater than NoAnswerScore."));
//                }

//                //检测必填字段
//                if (string.IsNullOrEmpty(botImportDataEx.Bot.TextWhenAgentIsOffline))
//                {
//                    errorMessages.Add(string.Format("the TextWhenAgentIsOffline is required."));
//                }
//                if (string.IsNullOrEmpty(botImportDataEx.Bot.TextWhenAgentIsOnline))
//                {
//                    errorMessages.Add(string.Format("the TextWhenAgentIsOnline is required."));
//                }
//                if (string.IsNullOrEmpty(botImportDataEx.Bot.TransferAgentMessage))
//                {
//                    errorMessages.Add(string.Format("the TransferAgentMessage is required."));
//                }
//                if (string.IsNullOrEmpty(botImportDataEx.Bot.LeaveAMessageClickedMessage))
//                {
//                    errorMessages.Add(string.Format("the LeaveAMessageClickedMessage is required."));
//                }
//                if (string.IsNullOrEmpty(botImportDataEx.Bot.RequestVisitorLocationMessage))
//                {
//                    errorMessages.Add(string.Format("the RequestVisitorLocationMessage is required."));
//                }
//                if (string.IsNullOrEmpty(botImportDataEx.Bot.LocationButtonText))
//                {
//                    errorMessages.Add(string.Format("the LocationButtonText is required."));
//                }
//                if (string.IsNullOrEmpty(botImportDataEx.Bot.SubmitButtonText))
//                {
//                    errorMessages.Add(string.Format("the SubmitButtonText is required."));
//                }
//                if (string.IsNullOrEmpty(botImportDataEx.Bot.CancelButtonText))
//                {
//                    errorMessages.Add(string.Format("the CancelButtonText is required."));
//                }
//                if (string.IsNullOrEmpty(botImportDataEx.Bot.ConfirmButtonText))
//                {
//                    errorMessages.Add(string.Format("the ConfirmButtonText is required."));
//                }

//                XmlDocument xmlDocument = new XmlDocument();
//                xmlDocument.LoadXml(xml);

//                //检测bool类型必须是true，false
//                string[] enumBoolArray = new string[] { "true", "false" };
//                string xpath = "//IsShowAgentLinkWhenNoResponse";
//                XmlNodeList isShowAgentLinkWhenNoResponseList = xmlDocument.SelectNodes(xpath);
//                if (isShowAgentLinkWhenNoResponseList != null)
//                {
//                    foreach (XmlNode node in isShowAgentLinkWhenNoResponseList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IsShowAgentLinkWhenNoResponse value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }
//                xpath = "//IsShowAgentLinkWhenNoResponse";
//                XmlNodeList isShowAgentLinkWhenNotHelpfulList = xmlDocument.SelectNodes(xpath);
//                if (isShowAgentLinkWhenNotHelpfulList != null)
//                {
//                    foreach (XmlNode node in isShowAgentLinkWhenNotHelpfulList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IsShowAgentLinkWhenNoResponse value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }
//                xpath = "//IsShowAgentLinkWhenPossibleResponsesThreshold";
//                XmlNodeList isShowAgentLinkWhenPossibleResponsesThresholdList = xmlDocument.SelectNodes(xpath);
//                if (isShowAgentLinkWhenPossibleResponsesThresholdList != null)
//                {
//                    foreach (XmlNode node in isShowAgentLinkWhenPossibleResponsesThresholdList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IsShowAgentLinkWhenPossibleResponsesThreshold value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }
//                xpath = "//IsNeedSingInBeforeBotRespond";
//                XmlNodeList isNeedSingInBeforeBotRespondList = xmlDocument.SelectNodes(xpath);
//                if (isNeedSingInBeforeBotRespondList != null)
//                {
//                    foreach (XmlNode node in isNeedSingInBeforeBotRespondList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IsNeedSingInBeforeBotRespond value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }
//                xpath = "//IsNotifyAgent";
//                XmlNodeList isNotifyAgentList = xmlDocument.SelectNodes(xpath);
//                if (isNotifyAgentList != null)
//                {
//                    foreach (XmlNode node in isNotifyAgentList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IsNotifyAgent value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }
//                xpath = "//IfRequireConfirm";
//                XmlNodeList ifRequireConfirmList = xmlDocument.SelectNodes(xpath);
//                if (ifRequireConfirmList != null)
//                {
//                    foreach (XmlNode node in ifRequireConfirmList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IfRequireConfirm value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }
//                xpath = "//IfRequireDetailInfo";
//                XmlNodeList ifRequireDetailInfoList = xmlDocument.SelectNodes(xpath);
//                if (ifRequireDetailInfoList != null)
//                {
//                    foreach (XmlNode node in ifRequireDetailInfoList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IfRequireDetailInfo value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }
//                xpath = "//IfRequireLocation";
//                XmlNodeList ifRequireLocationList = xmlDocument.SelectNodes(xpath);
//                if (ifRequireLocationList != null)
//                {
//                    foreach (XmlNode node in ifRequireLocationList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IfRequireLocation value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }
//                xpath = "//IsSSO";
//                XmlNodeList isSSOList = xmlDocument.SelectNodes(xpath);
//                if (isSSOList != null)
//                {
//                    foreach (XmlNode node in isSSOList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IsSSO value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }
//                xpath = "//IsRequired";
//                XmlNodeList isRequiredList = xmlDocument.SelectNodes(xpath);
//                if (isRequiredList != null)
//                {
//                    foreach (XmlNode node in isRequiredList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IsRequired value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }
//                xpath = "//IsMasked";
//                XmlNodeList isMaskedList = xmlDocument.SelectNodes(xpath);
//                if (isMaskedList != null)
//                {
//                    foreach (XmlNode node in isMaskedList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IsMasked value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }
//                xpath = "//IsEnabled";
//                XmlNodeList isEnabledList = xmlDocument.SelectNodes(xpath);
//                if (isEnabledList != null)
//                {
//                    foreach (XmlNode node in isEnabledList)
//                    {
//                        if (!enumBoolArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the IsEnabled value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }

//                ////检测AnswerSignInSettings的 ChannelType               
//                ////检测IntentAnswers的ChannelType
//                //xpath = "//ChannelType";
//                //XmlNodeList channelTypeList = xmlDocument.SelectNodes(xpath);
//                //if (channelTypeList != null)
//                //{
//                //    foreach (XmlNode node in channelTypeList)
//                //    {
//                //        if (!enumChannelTypeArray.Contains(node.InnerText))
//                //        {
//                //            errorMessages.Add(string.Format("the ChannelType value of '{0}' is invalid.", node.InnerText));
//                //        }
//                //    }
//                //}

//                //检测OpenIn
//                string[] enumOpenInArray = Enum.GetNames(typeof(Com.Comm100.Public.Enum.EnumOpenIn));
//                xpath = "//OpenIn";
//                XmlNodeList openInList = xmlDocument.SelectNodes(xpath);
//                if (openInList != null)
//                {
//                    foreach (XmlNode node in openInList)
//                    {
//                        if (!string.IsNullOrEmpty(node.InnerText) && !enumOpenInArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the OpenIn value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }

//                //检测CategoryName长度
//                xpath = "//CatagoryName";
//                XmlNodeList catagoryNameList = xmlDocument.SelectNodes(xpath);
//                if (catagoryNameList != null)
//                {
//                    foreach (XmlNode node in catagoryNameList)
//                    {
//                        if (!string.IsNullOrEmpty(node.InnerText))
//                        {
//                            string[] catagoryNameArray = node.InnerText.Split('/');
//                            foreach (string catagoryName in catagoryNameArray)
//                            {
//                                if (Encoding.UTF8.GetByteCount(catagoryName) > 128)
//                                {
//                                    errorMessages.Add(string.Format("The length of CatagoryName should be less than 128."));
//                                }
//                            }
//                        }
//                        else
//                        {
//                            errorMessages.Add(string.Format("the CatagoryName is required."));
//                        }
//                    }
//                }

//                //检测OpenIn
//                string[] enumOpenStyleArray = Enum.GetNames(typeof(Com.Comm100.Public.Enum.EnumOpenStyle));
//                xpath = "//OpenStyle";
//                XmlNodeList openStyleList = xmlDocument.SelectNodes(xpath);
//                if (openStyleList != null)
//                {
//                    foreach (XmlNode node in openStyleList)
//                    {
//                        if (!string.IsNullOrEmpty(node.InnerText) && !enumOpenStyleArray.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the OpenStyle value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }

//                xpath = "//QuestionEntity/EntityName";
//                XmlNodeList entitynameOfQuestionEntityList = xmlDocument.SelectNodes(xpath);
//                if (entitynameOfQuestionEntityList != null)
//                {
//                    foreach (XmlNode node in entitynameOfQuestionEntityList)
//                    {
//                        if (!(botImportDataEx.Bot.Entity.Any(a => a.EntityName == node.InnerText)))
//                        {
//                            errorMessages.Add(string.Format("question entity name[{0}] not exists", node.InnerText));
//                        }

//                        //xpath = "//Entity/EntityName[text()='" + node.InnerText + "']";
//                        //if (xmlDocument.SelectSingleNode(xpath) == null)
//                        //{
//                        //    errorMessages.Add(string.Format("question entity name[{0}] not exists", node.InnerText));
//                        //}
//                    }
//                }
//                xpath = "//EntityCollectionFormFields/EntityName";
//                XmlNodeList entityCollectionFormFields = xmlDocument.SelectNodes(xpath);
//                if (entityCollectionFormFields != null)
//                {
//                    foreach (XmlNode node in entityCollectionFormFields)
//                    {
//                        if (!string.IsNullOrEmpty(node.InnerText))
//                        {
//                            if (!(botImportDataEx.Bot.Entity.Any(a => a.EntityName == node.InnerText)))
//                            {
//                                errorMessages.Add(string.Format("entity collection form field entity name[{0}] not exists", node.InnerText));
//                            }
//                        }

//                        //xpath = "//Entity/EntityName[text()='" + node.InnerText + "']";
//                        //if (xmlDocument.SelectSingleNode(xpath) == null)
//                        //{
//                        //    errorMessages.Add(string.Format("entity collection form field entity name[{0}] not exists", node.InnerText));
//                        //}
//                    }
//                }
//                xpath = "//EntityCollectionPrompts/EntityName";
//                XmlNodeList entityCollectionPrompts = xmlDocument.SelectNodes(xpath);
//                if (entityCollectionPrompts != null)
//                {
//                    foreach (XmlNode node in entityCollectionPrompts)
//                    {
//                        if (!(botImportDataEx.Bot.Entity.Any(a => a.EntityName == node.InnerText)))
//                        {
//                            errorMessages.Add(string.Format("entity collection prompt field entity name[{0}] not exists", node.InnerText));
//                        }

//                        //xpath = "//Entity/EntityName[text()='" + node.InnerText + "']";
//                        //if (xmlDocument.SelectSingleNode(xpath) == null)
//                        //{
//                        //    errorMessages.Add(string.Format("entity collection prompt field entity name[{0}] not exists", node.InnerText));
//                        //}
//                    }
//                }
//                xpath = "//QuickReplyItems/IntentName";
//                XmlNodeList quickReplyItems = xmlDocument.SelectNodes(xpath);
//                if (quickReplyItems != null)
//                {
//                    foreach (XmlNode node in quickReplyItems)
//                    {
//                        if (!(botImportDataEx.Bot.Category.SelectMany(a => a.Intent).Any(a => a.IntentName == node.InnerText)))
//                        {
//                            errorMessages.Add(string.Format("quick reply items intent name[{0}] not exists", node.InnerText));
//                        }

//                        //xpath = "//Intent/IntentName[text()='" + node.InnerText + "']";
//                        //if (xmlDocument.SelectSingleNode(xpath) == null)
//                        //{
//                        //    errorMessages.Add(string.Format("quick reply items intent name[{0}] not exists", node.InnerText));
//                        //}
//                    }
//                }

//                xpath = "//Intent/EntityCollectionType";
//                XmlNodeList intents = xmlDocument.SelectNodes(xpath);
//                if (intents != null)
//                {
//                    string[] collectionTypes = new string[] { "form", "prompt" };
//                    foreach (XmlNode node in intents)
//                    {
//                        if (!string.IsNullOrEmpty(node.InnerText) && !collectionTypes.Contains(node.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the EntityCollectionType value of '{0}' is invalid.", node.InnerText));
//                        }
//                    }
//                }

//                //检测Entity
//                xpath = "//Entity";
//                XmlNodeList entityList = xmlDocument.SelectNodes(xpath);
//                if (entityList != null)
//                {
//                    List<string> entityNameList = new List<string>();
//                    foreach (XmlNode node in entityList)
//                    {
//                        xpath = "EntityType";
//                        XmlNode entityTypeNode = node.SelectSingleNode(xpath);
//                        if (entityTypeNode != null && !string.IsNullOrEmpty(entityTypeNode.InnerText))
//                        {
//                            string entityType = entityTypeNode.InnerText;
//                            if (entityType == "Prebuilt")
//                            {
//                                //系统的Entity 不参与校验
//                            }
//                            else
//                            {

//                                xpath = "EntityName";
//                                XmlNode entityNameNode = node.SelectSingleNode(xpath);
//                                if (entityNameNode != null && !string.IsNullOrEmpty(entityNameNode.InnerText))
//                                {
//                                    string entityName = entityNameNode.InnerText;
//                                    if (entityNameList.Contains(entityName))
//                                    {
//                                        //Entity Name 重复
//                                        errorMessages.Add(string.Format("Entity name '{0}' duplicate.", entityName));
//                                    }
//                                    else
//                                    {
//                                        entityNameList.Add(entityName);
//                                    }

//                                    if (entityName.Trim().ToLower() == "default")
//                                    {
//                                        errorMessages.Add(string.Format("Entity name cannot be default."));
//                                    }
//                                    else if (Encoding.UTF8.GetByteCount(entityName) > 30)
//                                    {
//                                        errorMessages.Add(string.Format("The length of entity name '{0}' should be less than 31.", entityName));
//                                    }
//                                    else
//                                    {
//                                        if (!Regex.IsMatch(entityName, @"^(?![0-9_-])[a-zA-Z0-9_-]*[a-zA-Z0-9]{1,30}$"))
//                                        {
//                                            errorMessages.Add(string.Format("Entity name may contain only the following:A-Z,a-z,0-9,_,-.And it should start with a letter.And it can't end by _."));
//                                        }
//                                    }
//                                }
//                                else
//                                {
//                                    errorMessages.Add(string.Format("{0} is required.", "Entity Name"));
//                                }

//                                xpath = "EntityItem";
//                                XmlNodeList entityItemList = node.SelectNodes(xpath);
//                                if (entityItemList != null)
//                                {
//                                    List<string> keywordList = new List<string>();
//                                    foreach (XmlNode itemNode in entityItemList)
//                                    {
//                                        xpath = "KeyWord";
//                                        XmlNode keyWordNode = itemNode.SelectSingleNode(xpath);
//                                        string keyword = keyWordNode.InnerText;

//                                        xpath = "SynonymsOfKeyWord";
//                                        string synoymsOfKeyWord = "";
//                                        XmlNode synoymsOfKeyWordNode = itemNode.SelectSingleNode(xpath);
//                                        if (synoymsOfKeyWordNode != null && !string.IsNullOrEmpty(synoymsOfKeyWordNode.InnerText))
//                                        {
//                                            synoymsOfKeyWord = synoymsOfKeyWordNode.InnerText;
//                                        }
//                                        else
//                                        {
//                                            synoymsOfKeyWord = keyword;
//                                        }

//                                        if (!synoymsOfKeyWord.Split(',').Contains(keyword))
//                                        {
//                                            synoymsOfKeyWord += string.Format(",{0}", keyword);
//                                        }

//                                        if (keywordList.Contains(keyword))
//                                        {
//                                            //Entity Name 重复
//                                            errorMessages.Add(string.Format("Keyword duplicate."));
//                                        }
//                                        else
//                                        {
//                                            keywordList.Add(keyword);
//                                        }

//                                        if (string.IsNullOrEmpty(keyword))
//                                        {
//                                            errorMessages.Add(string.Format("The {0} should not be empty.", "keyword"));
//                                        }
//                                        if (!string.IsNullOrEmpty(keyword) && Encoding.UTF8.GetByteCount(keyword) > 128)
//                                        {
//                                            errorMessages.Add(string.Format("The length of {0} should be less than 129.", "keyword"));
//                                        }
//                                        if (!string.IsNullOrEmpty(keyword) && !CheckKeyword_SynonymsValidation(keyword))
//                                        {
//                                            errorMessages.Add(@"Keyword cannot include \\,<,>,^,(,),|;cannot begin with @ or _;cannot end with _;}{,][,\""\"" should be only appear in pairs and cannot be empty.");
//                                        }
//                                        if (!string.IsNullOrEmpty(synoymsOfKeyWord) && synoymsOfKeyWord.Trim().StartsWith("@"))
//                                        {
//                                            errorMessages.Add(string.Format("The {0} should not start with @.", "synonyms"));
//                                        }
//                                        if (!string.IsNullOrEmpty(synoymsOfKeyWord) && Encoding.UTF8.GetByteCount(synoymsOfKeyWord) > 4000)
//                                        {
//                                            errorMessages.Add(string.Format("The total length of {0} should be less than 4001.", "synonyms"));
//                                        }

//                                        List<string> listSynonyms = string.IsNullOrWhiteSpace(synoymsOfKeyWord) ? new List<string>() : synoymsOfKeyWord.Replace('|', ',').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

//                                        if (listSynonyms == null || listSynonyms.Count == 0)
//                                        {
//                                            errorMessages.Add(string.Format("The {0} item should not be empty.", "synonyms"));
//                                        }
//                                        else
//                                        {
//                                            if (listSynonyms.Where(m => Encoding.UTF8.GetByteCount(m) > 128).Count() > 0)
//                                            {
//                                                errorMessages.Add(string.Format("The length of any {0} item should be less than 129.", "synonyms"));
//                                            }
//                                        }

//                                        listSynonyms.ForEach(delegate (string synonym)
//                                        {
//                                            if (!CheckKeyword_SynonymsValidation(synonym))
//                                            {
//                                                errorMessages.Add(@"Synonyms cannot include \\,<,>,^,(,),|;cannot begin with @ or _;cannot end with _;}{,][,\""\"" should be only appear in pairs and cannot be empty.");
//                                            }
//                                        });
//                                    }
//                                }
//                            }
//                        }
//                        else
//                        {
//                            errorMessages.Add(string.Format("{0} is required.", "Entity Type"));
//                        }

//                    }
//                }


//                if (errorMessages.Count > 0)
//                {
//                    //存在枚举类型校验，后面转换会有异常，所以先抛出
//                    return errorMessages;
//                }

//                //检测GreetingMessage
//                xpath = "//GreetingMessage";
//                XmlNodeList greetingMessageList = xmlDocument.SelectNodes(xpath);
//                foreach (XmlNode node in greetingMessageList)
//                {
//                    xpath = "ChannelType";
//                    XmlNode channelTypeNode = node.SelectSingleNode(xpath);
//                    if (channelTypeNode != null)
//                    {
//                        if (string.IsNullOrEmpty(channelTypeNode.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the channelType of greeting message is required."));
//                        }
//                        //else if (!enumChannelTypeArray.Contains(channelTypeNode.InnerText))
//                        //{
//                        //    errorMessages.Add(string.Format("the channelType of greeting message is invalid."));
//                        //}
//                    }

//                    xpath = "Type";
//                    XmlNode typeNode = node.SelectSingleNode(xpath);
//                    if (typeNode != null)
//                    {
//                        if (string.IsNullOrEmpty(typeNode.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the type of greeting message is required."));
//                        }
//                        else if (!Enum.GetNames(typeof(Com.Comm100.Public.Enum.EnumAnswerType)).Contains(typeNode.InnerText))
//                        {
//                            errorMessages.Add(string.Format("the type of greeting message is invalid."));
//                        }
//                    }

//                    xpath = "Buttons";
//                    XmlNodeList buttonList = node.SelectNodes(xpath);
//                    if (buttonList != null)
//                    {
//                        foreach (XmlNode buttonNode in buttonList)
//                        {
//                            xpath = "Type";
//                            XmlNode buttonTypeNode = buttonNode.SelectSingleNode(xpath);
//                            if (string.IsNullOrEmpty(buttonTypeNode.InnerText))
//                            {
//                                errorMessages.Add(string.Format("the type of button in greeting message is required."));
//                            }
//                            else if (!Enum.GetNames(typeof(Com.Comm100.Public.Enum.EnumButtonType)).Contains(buttonTypeNode.InnerText))
//                            {
//                                errorMessages.Add(string.Format("the type of button in of greeting message is invalid."));
//                            }
//                            else if (buttonTypeNode.InnerText == "goToIntent")
//                            {
//                                xpath = "UrlOrIntentName";
//                                XmlNode urlOrIntentNameNode = buttonNode.SelectSingleNode(xpath);
//                                if (string.IsNullOrEmpty(urlOrIntentNameNode.InnerText))
//                                {
//                                    errorMessages.Add(string.Format("the type of button in greeting message is goToIntent then UrlOrIntentName is required."));
//                                }
//                                else
//                                {
//                                    //检测 intentName是否有效
//                                    if (!(botImportDataEx.Bot.Category.SelectMany(a => a.Intent).Any(a => a.IntentName == urlOrIntentNameNode.InnerText)))
//                                    {
//                                        errorMessages.Add(string.Format("the urlOrIntentName of button in greeting message, intent name[{0}] not exists", urlOrIntentNameNode.InnerText));
//                                    }
//                                    //xpath = "//Intent/IntentName[text()='" + urlOrIntentNameNode.InnerText + "']";
//                                    //if (xmlDocument.SelectSingleNode(xpath) == null)
//                                    //{
//                                    //    errorMessages.Add(string.Format("the urlOrIntentName of button in greeting message, intent name[{0}] not exists", urlOrIntentNameNode.InnerText));
//                                    //}
//                                }

//                            }
//                        }
//                    }
//                }
//                if (botImportDataEx.Bot.GreetingMessage != null)
//                {
//                    Dictionary<string, List<Response>> greetingMessageKeyValuePairs = new Dictionary<string, List<Response>>();
//                    greetingMessageKeyValuePairs = botImportDataEx.Bot.GreetingMessage.ToLookup(k => k.ChannelType, v => v)
//                        .ToDictionary(k => k.Key, v =>
//                        {
//                            //BotAnswerSignInSettingTypeEx botAnswerSignInSettingTypeEx = botIntentTypeEx.AnswerSignInSettings.FirstOrDefault(a => a.ChannelType == v.Key);
//                            List<Response> responseList = new List<Response>();
//                            //BotIntentAnswerTypeEx[] botIntentAnswerTypeList = botIntentTypeEx.IntentAnswers.Where(a => a.ChannelType == v.ChannelType).ToArray();
//                            //if (botIntentAnswerTypeList != null)
//                            //{
//                            foreach (AnswerTypeEx greetingMessageAnswerTypeEx in v)
//                            {
//                                EnumAnswerType? enumAnswerType = null;
//                                enumAnswerType = (EnumAnswerType)Enum.Parse(typeof(EnumAnswerType), greetingMessageAnswerTypeEx.Type.ToString());
//                                object content = null;
//                                switch (enumAnswerType)
//                                {
//                                    case EnumAnswerType.text:
//                                        {
//                                            content = new TextResponse
//                                            {
//                                                texts = greetingMessageAnswerTypeEx.Content.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.RemoveEmptyEntries)
//                                            };
//                                            break;
//                                        }
//                                    case EnumAnswerType.button:
//                                        {
//                                            List<Button> buttonList = new List<Button>();
//                                            if (greetingMessageAnswerTypeEx.Buttons != null)
//                                            {
//                                                foreach (ButtonTypeEx botIntentAnswerButtonTypeEx in greetingMessageAnswerTypeEx.Buttons)
//                                                {
//                                                    EnumOpenIn? openIn = null;
//                                                    EnumOpenStyle? openStyle = null;

//                                                    if (!string.IsNullOrEmpty(botIntentAnswerButtonTypeEx.OpenIn))
//                                                    {
//                                                        openIn = (EnumOpenIn)Enum.Parse(typeof(EnumOpenIn), botIntentAnswerButtonTypeEx.OpenIn);
//                                                    }
//                                                    if (!string.IsNullOrEmpty(botIntentAnswerButtonTypeEx.OpenStyle))
//                                                    {
//                                                        openStyle = (EnumOpenStyle)Enum.Parse(typeof(EnumOpenStyle), botIntentAnswerButtonTypeEx.OpenStyle);
//                                                    }

//                                                    buttonList.Add(new Button
//                                                    {
//                                                        intentName = botIntentAnswerButtonTypeEx.UrlOrIntentName,
//                                                        linkUrl = botIntentAnswerButtonTypeEx.UrlOrIntentName,
//                                                        text = botIntentAnswerButtonTypeEx.Text,
//                                                        type = (EnumButtonType)Enum.Parse(typeof(EnumButtonType), botIntentAnswerButtonTypeEx.Type.ToString()),
//                                                        openIn = openIn,
//                                                        openStyle = openStyle,
//                                                    });
//                                                }
//                                            }
//                                            content = new ButtonResponse
//                                            {
//                                                text = greetingMessageAnswerTypeEx.Content,
//                                                buttons = buttonList.ToArray()
//                                            };
//                                            break;
//                                        }
//                                    case EnumAnswerType.image:
//                                    case EnumAnswerType.file:
//                                        {
//                                            string[] imageArr = greetingMessageAnswerTypeEx.Content?.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.RemoveEmptyEntries);
//                                            string name = "";
//                                            string url = "";
//                                            if (imageArr != null && imageArr.Length > 0)
//                                            {
//                                                name = imageArr[0];
//                                            }
//                                            if (imageArr != null && imageArr.Length > 1)
//                                            {
//                                                url = imageArr[1];
//                                            }

//                                            if (imageArr == null || imageArr.Length != 2)
//                                            {
//                                                errorMessages.Add(string.Format("when AnswerType is image or file then answer must format is 'name⊙url'."));
//                                            }

//                                            content = new ImageResponse
//                                            {
//                                                name = name,
//                                                url = url
//                                            };
//                                            break;
//                                        }
//                                    case EnumAnswerType.video:
//                                        {
//                                            content = new VideoResponse
//                                            {
//                                                url = greetingMessageAnswerTypeEx.Content
//                                            };
//                                            break;
//                                        }
//                                    case EnumAnswerType.webhook:
//                                        {
//                                            content = new WebhookResponse
//                                            {
//                                                url = greetingMessageAnswerTypeEx.Content
//                                            };
//                                            break;
//                                        }
//                                    case EnumAnswerType.quickReply:
//                                        {
//                                            string[] quickReplyArr = greetingMessageAnswerTypeEx.Content?.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.None);
//                                            string name = "";
//                                            string text = "";
//                                            if (quickReplyArr != null && quickReplyArr.Length > 0)
//                                            {
//                                                text = quickReplyArr[0];
//                                            }
//                                            if (quickReplyArr != null && quickReplyArr.Length > 1)
//                                            {
//                                                name = quickReplyArr[1];
//                                            }

//                                            //if (quickReplyArr == null || quickReplyArr.Length != 2)
//                                            //{
//                                            //    errorMessages.Add(string.Format("when AnswerType is quickReply then answer must format is 'answertype⊙quickReplyName' , but quickReplyName can't find in the xml."));
//                                            //}

//                                            List<QuickReplyItem> quickReplyItemList = new List<QuickReplyItem>();
//                                            BotQuickReplyTypeEx botQuickReplyTypeEx = botImportDataQueue.BotImportData.Bot.QuickReplys.FirstOrDefault(a => a.Name == name);
//                                            if (botQuickReplyTypeEx != null && botQuickReplyTypeEx.QuickReplyItems != null)
//                                            {
//                                                foreach (BotQuickReplyItemTypeEx botQuickReplyItemTypeEx in botQuickReplyTypeEx.QuickReplyItems)
//                                                {
//                                                    quickReplyItemList.Add(new QuickReplyItem
//                                                    {
//                                                        name = botQuickReplyItemTypeEx.ItemName,
//                                                        type = (EnumQuickReplyType)Enum.Parse(typeof(EnumQuickReplyType), botQuickReplyItemTypeEx.Type.ToString()),

//                                                    });
//                                                }
//                                            }
//                                            else
//                                            {
//                                                errorMessages.Add(string.Format("when AnswerType is quickReply then answer must format is 'answertype⊙quickReplyName' , but quickReplyName can't find in the xml."));
//                                            }

//                                            content = new ComplexQuickReplyResponse
//                                            {
//                                                agentOfflineText = botImportDataQueue.BotImportData.Bot.TextWhenAgentIsOffline,
//                                                agentOnlineText = botImportDataQueue.BotImportData.Bot.TextWhenAgentIsOnline,
//                                                text = text,
//                                                quickReplyItems = quickReplyItemList
//                                            };
//                                            break;
//                                        }
//                                    case EnumAnswerType.complex:
//                                        {
//                                            content = new ComplexResponse
//                                            {
//                                                text = greetingMessageAnswerTypeEx.Content
//                                            };
//                                            break;
//                                        }
//                                }

//                                responseList.Add(new Response
//                                {
//                                    type = enumAnswerType,
//                                    content = content
//                                });
//                            }
//                            //}

//                            //Com.Comm100.Public.Bot.AnswerSignInSettings answerSignInSettings = null;
//                            //    if (botAnswerSignInSettingTypeEx != null)
//                            //    {
//                            //        answerSignInSettings = new Com.Comm100.Public.Bot.AnswerSignInSettings
//                            //        {
//                            //            IsSSO = botAnswerSignInSettingTypeEx.IsSSO,
//                            //            SignInLinkText = botAnswerSignInSettingTypeEx.SignInLinkText,
//                            //            SignInMessage = botAnswerSignInSettingTypeEx.SignInMessage,
//                            //            SignInURL = botAnswerSignInSettingTypeEx.SignInURL,
//                            //            CustomVariable = botAnswerSignInSettingTypeEx.CustomVariable,
//                            //            OpenIn = (EnumOpenIn)botAnswerSignInSettingTypeEx.OpenIn
//                            //        };
//                            //    }

//                            //return new AnswerSubItem
//                            //{
//                            //    //IfNeedSignIn = botIntentTypeEx.IsNeedSingInBeforeBotRespond,
//                            //    //AnswerSignInSettings = answerSignInSettings,
//                            //    Responses = responseList,
//                            //};
//                            return responseList;
//                        });

//                    foreach (var key in greetingMessageKeyValuePairs.Keys)
//                    {
//                        if (greetingMessageKeyValuePairs[key] != null && greetingMessageKeyValuePairs.Count > 0)
//                        {
//                            if (greetingMessageKeyValuePairs[key].Count > 10)
//                                errorMessages.Add(APIHelper.GetErrorMessageByCode(50259).Message);
//                            var quickResponses = greetingMessageKeyValuePairs[key].Where(w => w.type == Com.Comm100.Public.Enum.EnumAnswerType.quickReply);
//                            if (quickResponses != null && quickResponses.Count() > 1)
//                                errorMessages.Add(APIHelper.GetErrorMessageByCode(51323).Message);
//                            if (quickResponses != null && quickResponses.Count() == 1)
//                            {
//                                Response quickResponse = quickResponses.FirstOrDefault();
//                                greetingMessageKeyValuePairs[key].Remove(quickResponse);
//                                greetingMessageKeyValuePairs[key].Add(quickResponse);
//                            }
//                            ErrorInfo errorInfo = null;
//                            foreach (var response in greetingMessageKeyValuePairs[key])
//                            {
//                                if (response.type == EnumAnswerType.webhook)
//                                {
//                                    errorMessages.Add(APIHelper.GetErrorMessageByCode(50257).Message);
//                                }
//                                errorInfo = ResponseValidation(response, key, botImportDataEx, isSupportComplex);
//                                if (errorInfo != null)
//                                {
//                                    errorMessages.Add(errorInfo.Message);
//                                }
//                            }
//                        }
//                    }
//                }

//                //设置SynonymsOfKeyWord 不包括 KeyWord，则添加到 SynonymsOfKeyWord 中
//                if (botImportDataQueue.BotImportData.Bot.Entity != null)
//                {
//                    if (botImportDataQueue.BotImportData.Bot.Entity.Count(a => a.EntityType == BotEntityTypeEntityType.List) > 249)
//                    {
//                        errorMessages.Add(APIHelper.GetErrorMessageByCode(52243).Message);
//                    }

//                    foreach (BotEntityTypeEx botEntityTypeEx in botImportDataQueue.BotImportData.Bot.Entity)
//                    {
//                        if (botEntityTypeEx.EntityItem != null)
//                        {
//                            foreach (BotListEntityItemTypeEx botListEntityItemTypeEx in botEntityTypeEx.EntityItem)
//                            {
//                                if (string.IsNullOrEmpty(botListEntityItemTypeEx.SynonymsOfKeyWord))
//                                {
//                                    botListEntityItemTypeEx.SynonymsOfKeyWord = botListEntityItemTypeEx.KeyWord;
//                                }
//                                else
//                                {
//                                    if (!botListEntityItemTypeEx.SynonymsOfKeyWord.Split(',').Contains(botListEntityItemTypeEx.KeyWord))
//                                    {
//                                        botListEntityItemTypeEx.SynonymsOfKeyWord += string.Format(",{0}", botListEntityItemTypeEx.KeyWord);
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }

//                ////检测Intent
//                //xpath = "//Intent";
//                //intents = xmlDocument.SelectNodes(xpath);
//                //if (intents != null)
//                //{
//                //    foreach (XmlNode node in intents)
//                //    {
//                //        xpath = "IfRequireDetailInfo[text()='true']";
//                //        if (node.SelectSingleNode(xpath) != null)
//                //        {
//                //            xpath = "EntityCollectionType";
//                //            if (node.SelectSingleNode(xpath) == null || string.IsNullOrEmpty(node.SelectSingleNode(xpath).InnerText))
//                //            {
//                //                errorMessages.Add(string.Format("when IfRequireDetailInfo is true then EntityCollectionType is required."));
//                //            }
//                //        }

//                //    }
//                //}

//                List<string> intentNameList = new List<string>();

//                if (botImportDataQueue.BotImportData.Bot.Category != null)
//                {
//                    foreach (BotCategoryTypeEx botCategoryTypeEx in botImportDataQueue.BotImportData.Bot.Category)
//                    {
//                        if (botCategoryTypeEx.Intent != null)
//                        {
//                            foreach (BotIntentTypeEx botIntentTypeEx in botCategoryTypeEx.Intent)
//                            {
//                                try
//                                {
//                                    if (intentNameList.Contains(botIntentTypeEx.IntentName.ToLower()))
//                                    {
//                                        errorMessages.Add(string.Format("Intent name '{0}' duplicate.", botIntentTypeEx.IntentName));
//                                    }
//                                    else
//                                    {
//                                        intentNameList.Add(botIntentTypeEx.IntentName.ToLower());
//                                    }

//                                    List<KeyValuePair<string, string>> keyValueEntityLabel = new List<KeyValuePair<string, string>>();

//                                    EnumEntityCollectionType? entityCollectionType = null;
//                                    if (!string.IsNullOrEmpty(botIntentTypeEx.EntityCollectionType))
//                                    {
//                                        string[] collectionTypes = new string[] { "form", "prompt" };
//                                        if (collectionTypes.Contains(botIntentTypeEx.EntityCollectionType))
//                                        {
//                                            entityCollectionType = (EnumEntityCollectionType)Enum.Parse(typeof(EnumEntityCollectionType), botIntentTypeEx.EntityCollectionType);
//                                        }
//                                    }
//                                    List<Com.Comm100.Public.Bot.Question> questions = new List<Com.Comm100.Public.Bot.Question>();
//                                    if (botIntentTypeEx.Question != null)
//                                    {
//                                        foreach (BotIntentQuestionTypeEx botIntentQuestionTypeEx in botIntentTypeEx.Question)
//                                        {
//                                            List<EntityLabel> entityLabels = new List<EntityLabel>();
//                                            if (botIntentQuestionTypeEx.QuestionEntity != null)
//                                            {
//                                                foreach (BotIntentQuestionEntityTypeEx botIntentQuestionEntityTypeEx in botIntentQuestionTypeEx.QuestionEntity)
//                                                {
//                                                    entityLabels.Add(new EntityLabel
//                                                    {
//                                                        Label = botIntentQuestionEntityTypeEx.EntityLabel,
//                                                        StartPos = botIntentQuestionEntityTypeEx.StartPos,
//                                                        EndPos = botIntentQuestionEntityTypeEx.EndPos,
//                                                    });

//                                                    keyValueEntityLabel.Add(new KeyValuePair<string, string>(
//                                                        botIntentQuestionEntityTypeEx.EntityName, botIntentQuestionEntityTypeEx.EntityLabel));
//                                                }
//                                            }
//                                            questions.Add(new Com.Comm100.Public.Bot.Question
//                                            {
//                                                Text = botIntentQuestionTypeEx.Content,
//                                                EntityLabels = entityLabels,
//                                            });
//                                        }
//                                    }
//                                    Dictionary<string, AnswerSubItem> keyValuePairs = new Dictionary<string, AnswerSubItem>();
//                                    keyValuePairs = botIntentTypeEx.IntentAnswers.Where(a => !string.IsNullOrEmpty(a.ChannelType)).ToLookup(k => k.ChannelType, v => v)
//                                        .ToDictionary(k => k.Key, v =>
//                                        {
//                                            BotAnswerSignInSettingTypeEx botAnswerSignInSettingTypeEx = botIntentTypeEx.AnswerSignInSettings.FirstOrDefault(a => a.ChannelType == v.Key);
//                                            List<Response> responseList = new List<Response>();
//                                            //BotIntentAnswerTypeEx[] botIntentAnswerTypeList = botIntentTypeEx.IntentAnswers.Where(a => a.ChannelType == v.ChannelType).ToArray();
//                                            //if (botIntentAnswerTypeList != null)
//                                            //{
//                                            foreach (BotIntentAnswerTypeEx botIntentAnswerTypeEx in v)
//                                            {
//                                                EnumAnswerType? enumAnswerType = null;
//                                                enumAnswerType = (EnumAnswerType)Enum.Parse(typeof(EnumAnswerType), botIntentAnswerTypeEx.AnswerType.ToString());
//                                                object content = null;
//                                                switch (enumAnswerType)
//                                                {
//                                                    case EnumAnswerType.text:
//                                                        {
//                                                            content = new TextResponse
//                                                            {
//                                                                texts = botIntentAnswerTypeEx.Answer?.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.RemoveEmptyEntries)
//                                                            };
//                                                            break;
//                                                        }
//                                                    case EnumAnswerType.button:
//                                                        {
//                                                            List<Button> buttonList = new List<Button>();
//                                                            if (botIntentAnswerTypeEx.IntentAnswerButtons != null)
//                                                            {
//                                                                foreach (BotIntentAnswerButtonTypeEx botIntentAnswerButtonTypeEx in botIntentAnswerTypeEx.IntentAnswerButtons)
//                                                                {
//                                                                    EnumOpenIn? openIn = null;
//                                                                    EnumOpenStyle? openStyle = null;

//                                                                    if (!string.IsNullOrEmpty(botIntentAnswerButtonTypeEx.OpenIn))
//                                                                    {
//                                                                        if (enumOpenInArray.Contains(botIntentAnswerButtonTypeEx.OpenIn))
//                                                                        {
//                                                                            openIn = (EnumOpenIn)Enum.Parse(typeof(EnumOpenIn), botIntentAnswerButtonTypeEx.OpenIn);
//                                                                        }
//                                                                    }
//                                                                    if (!string.IsNullOrEmpty(botIntentAnswerButtonTypeEx.OpenStyle))
//                                                                    {
//                                                                        if (enumOpenStyleArray.Contains(botIntentAnswerButtonTypeEx.OpenStyle))
//                                                                        {
//                                                                            openStyle = (EnumOpenStyle)Enum.Parse(typeof(EnumOpenStyle), botIntentAnswerButtonTypeEx.OpenStyle);
//                                                                        }
//                                                                    }

//                                                                    buttonList.Add(new Button
//                                                                    {
//                                                                        intentName = botIntentAnswerButtonTypeEx.UrlOrIntentName,
//                                                                        linkUrl = botIntentAnswerButtonTypeEx.UrlOrIntentName,
//                                                                        text = botIntentAnswerButtonTypeEx.ButtonText,
//                                                                        type = (EnumButtonType)Enum.Parse(typeof(EnumButtonType), botIntentAnswerButtonTypeEx.ButtonType.ToString()),
//                                                                        openIn = openIn,
//                                                                        openStyle = openStyle,
//                                                                    });
//                                                                }
//                                                            }
//                                                            content = new ButtonResponse
//                                                            {
//                                                                text = botIntentAnswerTypeEx.Answer,
//                                                                buttons = buttonList.ToArray()
//                                                            };
//                                                            break;
//                                                        }
//                                                    case EnumAnswerType.image:
//                                                    case EnumAnswerType.file:
//                                                        {
//                                                            string[] imageArr = botIntentAnswerTypeEx.Answer?.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.RemoveEmptyEntries);
//                                                            string name = "";
//                                                            string url = "";
//                                                            if (imageArr != null && imageArr.Length > 0)
//                                                            {
//                                                                name = imageArr[0];
//                                                            }
//                                                            if (imageArr != null && imageArr.Length > 1)
//                                                            {
//                                                                url = imageArr[1];
//                                                            }

//                                                            if (imageArr == null || imageArr.Length != 2)
//                                                            {
//                                                                errorMessages.Add(string.Format("when AnswerType is image or file then answer must format is 'name⊙url'."));
//                                                            }

//                                                            content = new ImageResponse
//                                                            {
//                                                                name = name,
//                                                                url = url
//                                                            };
//                                                            break;
//                                                        }
//                                                    case EnumAnswerType.video:
//                                                        {
//                                                            content = new VideoResponse
//                                                            {
//                                                                url = botIntentAnswerTypeEx.Answer
//                                                            };
//                                                            break;
//                                                        }
//                                                    case EnumAnswerType.webhook:
//                                                        {
//                                                            string url = "";
//                                                            Dictionary<string, string> headers = new Dictionary<string, string> { };
//                                                            if (botIntentAnswerTypeEx != null && !string.IsNullOrWhiteSpace(botIntentAnswerTypeEx.Answer))
//                                                            {
//                                                                string[] webhookArr = botIntentAnswerTypeEx.Answer.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.None);
//                                                                if (webhookArr != null && webhookArr.Length > 0 && !string.IsNullOrWhiteSpace(webhookArr[0]))
//                                                                {
//                                                                    url = webhookArr[0];
//                                                                }
//                                                                if (webhookArr != null && webhookArr.Length > 1 && !string.IsNullOrWhiteSpace(webhookArr[1]))
//                                                                {
//                                                                    headers = JsonConvert.DeserializeObject<Dictionary<string, string>>(System.Web.HttpUtility.HtmlDecode(webhookArr[1]));
//                                                                }
//                                                            }

//                                                            content = new WebhookResponse
//                                                            {
//                                                                url = url,
//                                                                headers = headers,
//                                                            };
//                                                            break;
//                                                        }
//                                                    case EnumAnswerType.quickReply:
//                                                        {
//                                                            string[] quickReplyArr = botIntentAnswerTypeEx.Answer?.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.None);
//                                                            string name = "";
//                                                            string text = "";
//                                                            if (quickReplyArr != null && quickReplyArr.Length > 0)
//                                                            {
//                                                                text = quickReplyArr[0];
//                                                            }
//                                                            if (quickReplyArr != null && quickReplyArr.Length > 1)
//                                                            {
//                                                                name = quickReplyArr[1];
//                                                            }
//                                                            List<QuickReplyItem> quickReplyItemList = new List<QuickReplyItem>();
//                                                            BotQuickReplyTypeEx botQuickReplyTypeEx = botImportDataQueue.BotImportData.Bot.QuickReplys.FirstOrDefault(a => a.Name == name);
//                                                            if (botQuickReplyTypeEx != null && botQuickReplyTypeEx.QuickReplyItems != null)
//                                                            {
//                                                                foreach (BotQuickReplyItemTypeEx botQuickReplyItemTypeEx in botQuickReplyTypeEx.QuickReplyItems)
//                                                                {
//                                                                    quickReplyItemList.Add(new QuickReplyItem
//                                                                    {
//                                                                        name = botQuickReplyItemTypeEx.ItemName,
//                                                                        type = (EnumQuickReplyType)Enum.Parse(typeof(EnumQuickReplyType), botQuickReplyItemTypeEx.Type.ToString()),

//                                                                    });
//                                                                }
//                                                            }
//                                                            content = new ComplexQuickReplyResponse
//                                                            {
//                                                                agentOfflineText = botImportDataQueue.BotImportData.Bot.TextWhenAgentIsOffline,
//                                                                agentOnlineText = botImportDataQueue.BotImportData.Bot.TextWhenAgentIsOnline,
//                                                                text = text,
//                                                                quickReplyItems = quickReplyItemList
//                                                            };
//                                                            break;
//                                                        }
//                                                    case EnumAnswerType.complex:
//                                                        {
//                                                            content = new ComplexResponse
//                                                            {
//                                                                text = botIntentAnswerTypeEx.Answer
//                                                            };
//                                                            break;
//                                                        }
//                                                }

//                                                responseList.Add(new Response
//                                                {
//                                                    type = enumAnswerType,
//                                                    content = content
//                                                });
//                                            }
//                                            //}

//                                            Com.Comm100.Public.Bot.AnswerSignInSettings answerSignInSettings = null;
//                                            if (botAnswerSignInSettingTypeEx != null)
//                                            {
//                                                //if (string.IsNullOrEmpty(botAnswerSignInSettingTypeEx.SignInURL))
//                                                //{
//                                                //    errorMessages.Add(string.Format("the SignInURL is required."));
//                                                //}
//                                                if (string.IsNullOrEmpty(botAnswerSignInSettingTypeEx.SignInMessage))
//                                                {
//                                                    errorMessages.Add(string.Format("the SignInMessage is required."));
//                                                }
//                                                if (string.IsNullOrEmpty(botAnswerSignInSettingTypeEx.SignInLinkText))
//                                                {
//                                                    errorMessages.Add(string.Format("the SignInLinkText is required."));
//                                                }

//                                                answerSignInSettings = new Com.Comm100.Public.Bot.AnswerSignInSettings
//                                                {
//                                                    IsSSO = botAnswerSignInSettingTypeEx.IsSSO,
//                                                    SignInLinkText = botAnswerSignInSettingTypeEx.SignInLinkText,
//                                                    SignInMessage = botAnswerSignInSettingTypeEx.SignInMessage,
//                                                    SignInURL = botAnswerSignInSettingTypeEx.SignInURL,
//                                                    CustomVariable = botAnswerSignInSettingTypeEx.CustomVariable,
//                                                    OpenIn = (EnumOpenIn)botAnswerSignInSettingTypeEx.OpenIn
//                                                };
//                                            }

//                                            return new AnswerSubItem
//                                            {
//                                                IfNeedSignIn = botAnswerSignInSettingTypeEx != null, //
//                                                AnswerSignInSettings = answerSignInSettings,
//                                                Responses = responseList,
//                                            };
//                                        });

//                                    List<EntityCollectionFormField> entityCollectionFormFieldList = new List<EntityCollectionFormField>();
//                                    if (botIntentTypeEx.EntityCollectionFormFields != null)
//                                    {
//                                        foreach (BotEntityCollectionFormFieldTypeEx botEntityCollectionFormFieldTypeEx in botIntentTypeEx.EntityCollectionFormFields)
//                                        {
//                                            entityCollectionFormFieldList.Add(new EntityCollectionFormField
//                                            {
//                                                FieldName = botEntityCollectionFormFieldTypeEx.FieldName,
//                                                FieldType = (Com.Comm100.Public.Enum.EnumFieldType)Enum.Parse(typeof(Com.Comm100.Public.Enum.EnumFieldType), botEntityCollectionFormFieldTypeEx.FieldType.ToString()),
//                                                Label = botEntityCollectionFormFieldTypeEx.EntityLabel,
//                                                IsMasked = botEntityCollectionFormFieldTypeEx.IsMasked,
//                                                IsRequired = botEntityCollectionFormFieldTypeEx.IsRequired,
//                                                Options = botEntityCollectionFormFieldTypeEx.Options?.ToList()
//                                            });

//                                            if (!string.IsNullOrEmpty(botEntityCollectionFormFieldTypeEx.EntityName) &&
//                                                !string.IsNullOrEmpty(botEntityCollectionFormFieldTypeEx.EntityLabel))
//                                            {
//                                                if (keyValueEntityLabel.Count(a => a.Key == botEntityCollectionFormFieldTypeEx.EntityName && a.Value == botEntityCollectionFormFieldTypeEx.EntityLabel) > 0)
//                                                {

//                                                }
//                                                else
//                                                {
//                                                    errorMessages.Add(string.Format("the entity label '{0}' can't find in the question entity list.", botEntityCollectionFormFieldTypeEx.EntityLabel));
//                                                }
//                                            }
//                                        }
//                                    }
//                                    EntityCollectionForm entityCollectionForm = new EntityCollectionForm
//                                    {
//                                        IfRequireConfirm = botIntentTypeEx.IfRequireConfirm,
//                                        FormTitle = botIntentTypeEx.FormTitle,
//                                        FormMessage = botIntentTypeEx.FormMessage,
//                                        FormFields = entityCollectionFormFieldList,
//                                    };

//                                    List<EntityCollectionPrompt> entityCollectionPromptList = new List<EntityCollectionPrompt>();
//                                    if (botIntentTypeEx.EntityCollectionPrompts != null)
//                                    {
//                                        foreach (BotEntityCollectionPromptTypeEx botEntityCollectionPromptTypeEx in botIntentTypeEx.EntityCollectionPrompts)
//                                        {
//                                            entityCollectionPromptList.Add(new EntityCollectionPrompt
//                                            {
//                                                Label = botEntityCollectionPromptTypeEx.EntityLabel,
//                                                Questions = botEntityCollectionPromptTypeEx.Questions?.ToList(),
//                                                Options = botEntityCollectionPromptTypeEx.Options?.ToList(),

//                                            });

//                                            if (keyValueEntityLabel.Count(a => a.Key == botEntityCollectionPromptTypeEx.EntityName && a.Value == botEntityCollectionPromptTypeEx.EntityLabel) > 0)
//                                            {

//                                            }
//                                            else
//                                            {
//                                                errorMessages.Add(string.Format("the entity label '{0}' can't find in the question entity list.", botEntityCollectionPromptTypeEx.EntityLabel));
//                                            }
//                                        }
//                                    }
//                                    Intent intent = new Intent
//                                    {
//                                        Name = botIntentTypeEx.IntentName,
//                                        IfRequireDetailInfo = botIntentTypeEx.IfRequireDetailInfo,
//                                        IfRequireLocation = botIntentTypeEx.IfRequireLocation,
//                                        EntityCollectionType = entityCollectionType,
//                                        Questions = questions,
//                                        Answer = keyValuePairs,
//                                        EntityCollectionForm = entityCollectionForm,
//                                        EntityCollectionPrompts = entityCollectionPromptList,
//                                    };

//                                    ErrorInfo errorInfo = IntentValidation(intent, isSupportComplex, botImportDataEx);
//                                    if (errorInfo != null && errorInfo.Code > 1)
//                                    {
//                                        //errorMessages.Add(errorInfo.Message); 暂时去掉数据校验 2019.11.25
//                                    }

//                                    //检测quickReplyName是否存在
//                                    if (botIntentTypeEx.IntentAnswers != null)
//                                    {
//                                        BotIntentAnswerTypeEx[] botIntentAnswerTypeList = botIntentTypeEx.IntentAnswers.Where(a => a.AnswerType == AnswerTypeType.quickReply).ToArray();
//                                        if (botIntentAnswerTypeList != null)
//                                        {
//                                            foreach (BotIntentAnswerTypeEx botIntentAnswerTypeEx in botIntentAnswerTypeList)
//                                            {
//                                                string[] quickReplayArr = botIntentAnswerTypeEx.Answer.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.None);
//                                                string name = "";
//                                                string text = "";
//                                                if (quickReplayArr != null && quickReplayArr.Length > 0)
//                                                {
//                                                    text = quickReplayArr[0];
//                                                }
//                                                if (quickReplayArr != null && quickReplayArr.Length > 1)
//                                                {
//                                                    name = quickReplayArr[1];
//                                                }

//                                                BotQuickReplyTypeEx botQuickReplyTypeEx = botImportDataQueue.BotImportData.Bot.QuickReplys.FirstOrDefault(a => a.Name == name);
//                                                if (botQuickReplyTypeEx == null)
//                                                {
//                                                    errorMessages.Add(string.Format("when AnswerType is quickReply then answer must format is 'answertype⊙quickReplyName' , but quickReplyName can't find in the xml."));
//                                                }
//                                            }
//                                        }

//                                        List<BotIntentTypeEx> botIntentTypeAll = botImportDataQueue.BotImportData.Bot.Category.SelectMany(a => a.Intent).ToList();
//                                        List<BotIntentAnswerButtonTypeEx> botIntentAnswerButtonTypeAll = botIntentTypeEx.IntentAnswers.SelectMany(a => a.IntentAnswerButtons)?.Where(a => a.ButtonType == ButtonTypeType.goToIntent).ToList();
//                                        foreach (BotIntentAnswerButtonTypeEx botIntentAnswerButtonTypeEx in botIntentAnswerButtonTypeAll)
//                                        {
//                                            if (string.IsNullOrEmpty(botIntentAnswerButtonTypeEx.UrlOrIntentName))
//                                            {
//                                                errorMessages.Add(string.Format("the type of button in intent answer button is goToIntent then UrlOrIntentName is required."));
//                                            }
//                                            else
//                                            {
//                                                BotIntentTypeEx botIntentTypeExFind = botIntentTypeAll.FirstOrDefault(a => a.IntentName == botIntentAnswerButtonTypeEx.UrlOrIntentName);
//                                                if (botIntentTypeExFind == null)
//                                                {
//                                                    errorMessages.Add(string.Format("the urlOrIntentName of button in intent answer button, intent name[{0}] not exists", botIntentAnswerButtonTypeEx.UrlOrIntentName));
//                                                }
//                                            }
//                                        }
//                                    }

//                                    // more than 20 different entityLabels.
//                                    if (botIntentTypeEx.Question.SelectMany(a => a.QuestionEntity).DistinctBy(a => new { a.EntityName, a.EntityLabel }).Count() > 20)
//                                        errorMessages.Add(APIHelper.GetErrorMessageByCode(51366).Message);
//                                }
//                                catch
//                                {
//                                    throw;
//                                }
//                            }

//                        }
//                    }
//                }

//                //检测SmartTriggers
//                if (botImportDataQueue.BotImportData.Bot.SmartTriggers != null)
//                {
//                    List<string> botSmartTriggerNameList = new List<string>();

//                    foreach (BotSmartTriggerTypeEx botSmartTriggerTypeEx in botImportDataQueue.BotImportData.Bot.SmartTriggers)
//                    {
//                        string botSmartTriggerName = botSmartTriggerTypeEx.Name;
//                        if (string.IsNullOrEmpty(botSmartTriggerName))
//                        {
//                            errorMessages.Add(string.Format("the Smart Trigger Name is required."));
//                        }
//                        else
//                        {
//                            if (!botSmartTriggerNameList.Contains(botSmartTriggerName))
//                            {
//                                botSmartTriggerNameList.Add(botSmartTriggerName);
//                            }
//                            else
//                            {
//                                //Entity Name 重复
//                                errorMessages.Add(string.Format("Smart Trigger Name duplicate."));
//                            }
//                        }

//                        List<SmartTriggerCondition> smartTriggerConditions = new List<SmartTriggerCondition>();
//                        if (botSmartTriggerTypeEx.SmartTriggerConditions != null)
//                        {
//                            foreach (BotSmartTriggerConditionTypeEx botSmartTriggerConditionTypeEx in botSmartTriggerTypeEx.SmartTriggerConditions)
//                            {
//                                smartTriggerConditions.Add(new SmartTriggerCondition
//                                {
//                                    Expression = (EnumConditionExpression)Enum.Parse(typeof(EnumConditionExpression), botSmartTriggerConditionTypeEx.Expression.ToString()),
//                                    Items = botSmartTriggerConditionTypeEx.Value.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.RemoveEmptyEntries).ToList(),
//                                    Variable = botSmartTriggerConditionTypeEx.Variable
//                                });
//                            }
//                        }
//                        Com.Comm100.Public.Bot.SmartTriggerConditions conditions = new Com.Comm100.Public.Bot.SmartTriggerConditions
//                        {
//                            Expression = botSmartTriggerTypeEx.ConditionExpression,
//                            Items = smartTriggerConditions,
//                            When = (EnumConditionWhen)Enum.Parse(typeof(EnumConditionWhen), botSmartTriggerTypeEx.ConditionExpressionType.ToString())
//                        };
//                        ErrorInfo errorInfo = CheckSmartTriggerValidation(conditions);
//                        if (errorInfo != null && errorInfo.Code > 1)
//                        {
//                            errorMessages.Add(errorInfo.Message);
//                        }

//                        IList<Com.Comm100.Public.Bot.SmartTriggerAction> actions = new List<Com.Comm100.Public.Bot.SmartTriggerAction>();
//                        if (botSmartTriggerTypeEx.SmartTriggerActions != null)
//                        {
//                            foreach (BotSmartTriggerActionTypeEx botSmartTriggerActionTypeEx in botSmartTriggerTypeEx.SmartTriggerActions)
//                            {
//                                List<Guid> agents = null;
//                                List<Guid> departments = null;

//                                if (botSmartTriggerActionTypeEx.Agents != null && botSmartTriggerActionTypeEx.Agents.Length > 0)
//                                {
//                                    if (!CheckArrayGuid(botSmartTriggerActionTypeEx.Agents))
//                                    {
//                                        errorMessages.Add(string.Format("the agents '{0}' in smart trigger action must number array. ", botSmartTriggerActionTypeEx.Agents));
//                                        botSmartTriggerActionTypeEx.Agents = new string[] { "00000000-0000-0000-0000-000000000000" };
//                                    }
//                                    else
//                                    {
//                                        agents = botSmartTriggerActionTypeEx.Agents.Select(a => Guid.Parse(a)).ToList();
//                                    }
//                                }

//                                if (botSmartTriggerActionTypeEx.Departments != null && botSmartTriggerActionTypeEx.Departments.Length > 0)
//                                {
//                                    if (!CheckArrayGuid(botSmartTriggerActionTypeEx.Departments))
//                                    {
//                                        errorMessages.Add(string.Format("the departments '{0}' in smart trigger action must number array. ", botSmartTriggerActionTypeEx.Departments));
//                                        botSmartTriggerActionTypeEx.Departments = new string[] { "00000000-0000-0000-0000-000000000000" };
//                                    }
//                                    else
//                                    {
//                                        departments = botSmartTriggerActionTypeEx.Departments.Select(a => Guid.Parse(a)).ToList();
//                                    }
//                                }

//                                actions.Add(new SmartTriggerAction
//                                {
//                                    AgentOfflineMessage = botSmartTriggerActionTypeEx.AgentOfflineMessage,
//                                    AgentOfflineText = botImportDataQueue.BotImportData.Bot.TextWhenAgentIsOffline,
//                                    IsEnabled = botSmartTriggerActionTypeEx.IsEnabled,
//                                    Target = new SmartTriggerTarget
//                                    {
//                                        Agents = agents,
//                                        Departments = departments,
//                                        VisitorSegmentId = Guid.Parse(botSmartTriggerActionTypeEx.VisitorSegmentId),
//                                        Type = (EnumTargetType)Enum.Parse(typeof(EnumTargetType), botSmartTriggerActionTypeEx.TargetType.ToString()),
//                                    },
//                                    Type = (EnumActionType)Enum.Parse(typeof(EnumActionType), botSmartTriggerActionTypeEx.ActionType.ToString()),
//                                });
//                            }
//                        }
//                        errorInfo = CheckSmartTriggerActionsValidation(actions);
//                        if (errorInfo != null && errorInfo.Code > 1)
//                        {
//                            errorMessages.Add(errorInfo.Message);
//                        }
//                    }
//                }

//                //检测 Quick Replay
//                List<string> quickReplayNameList = new List<string>();
//                if (botImportDataQueue.BotImportData.Bot.QuickReplys != null)
//                {
//                    foreach (BotQuickReplyTypeEx botQuickReplyTypeEx in botImportDataQueue.BotImportData.Bot.QuickReplys)
//                    {
//                        if (string.IsNullOrEmpty(botQuickReplyTypeEx.Name))
//                        {
//                            errorMessages.Add(string.Format("the QuickReplay Name is required."));
//                        }
//                        else
//                        {
//                            if (quickReplayNameList.Contains(botQuickReplyTypeEx.Name))
//                            {
//                                errorMessages.Add(string.Format("the QuickReplay Name duplicate."));
//                            }
//                            else
//                            {
//                                quickReplayNameList.Add(botQuickReplyTypeEx.Name);
//                            }
//                        }

//                        int errorCode = CheckQuickReplyItemValidation(botQuickReplyTypeEx);
//                        if (errorCode > 1)
//                        {
//                            errorMessages.Add(APIHelper.GetErrorMessageByCode(errorCode)?.Message);
//                        }

//                        if (botQuickReplyTypeEx.QuickReplyItems != null)
//                        {
//                            BotQuickReplyItemTypeEx[] botQuickReplyItemTypeGoToIntentList = botQuickReplyTypeEx.QuickReplyItems.Where(a => a.Type == BotQuickReplyItemTypeType.goToIntent).ToArray();
//                            foreach (BotQuickReplyItemTypeEx botQuickReplyItemTypeEx in botQuickReplyItemTypeGoToIntentList)
//                            {
//                                if (!string.IsNullOrEmpty(botQuickReplyItemTypeEx.IntentName))
//                                {
//                                    if (botImportDataQueue.BotImportData.Bot.Category.SelectMany(a => a.Intent).Count(a => a.IntentName == botQuickReplyItemTypeEx.IntentName) > 0)
//                                    {

//                                    }
//                                    else
//                                    {
//                                        errorMessages.Add(string.Format("the qickReply item '{0}' type is 'goToIntent' then IntentName is '{1}' not exists in then xml. ", botQuickReplyItemTypeEx.ItemName, botQuickReplyItemTypeEx.IntentName));
//                                    }
//                                }
//                                else
//                                {
//                                    errorMessages.Add(string.Format("the qickReply item '{0}' type is 'goToIntent' then IntentName is required. ", botQuickReplyItemTypeEx.ItemName));
//                                }
//                            }
//                        }
//                    }
//                }

//                botImportDataQueue.BotImportData.Bot.Id = bot.Id;
//                botImportDataQueue.BotImportData.Bot.BotEngineAppId = bot.BotEngineAppId;
//                botImportDataQueue.BotImportData.Bot.SiteId = bot.SiteId;

//                botImportDataQueue.SiteId = siteId;
//                botImportDataQueue.BotId = botId;
//                botImportDataQueue.BotName = botName;
//                botImportDataQueue.AppId = appId;

//            }
//            return errorMessages;
//        }
//        bool GetIsSupportComplex(int siteId, Guid botId)
//        {
//            bool boolResult = false;
//            return boolResult;
//        }
//        bool CheckKeyword_SynonymsValidation(string value)
//        {
//            if (!string.IsNullOrWhiteSpace(value))
//            {
//                if (value.IndexOfAny(new char[] { '\\', '<', '>', '^', '(', ')', '|' }) > -1)
//                    return false;
//                if (value.Trim().Substring(0, 1).IndexOfAny(new char[] { '@', '_' }) > -1 || value.Trim().EndsWith("_"))
//                    return false;
//                if (!(value.IndexOf('{') > -1 & value.IndexOf('}') > -1) && !(value.IndexOf('{') < 0 && value.IndexOf('}') < 0))
//                    return false;
//                if (!(value.IndexOf('[') > -1 & value.IndexOf(']') > -1) && !(value.IndexOf('[') < 0 && value.IndexOf(']') < 0))
//                    return false;
//                if (value.IndexOf('{') > -1 && value.IndexOf('}') > -1 && Math.Abs(value.IndexOf('{') - value.IndexOf('}')) == 1)
//                    return false;
//                if (value.IndexOf('[') > -1 && value.IndexOf(']') > -1 && Math.Abs(value.IndexOf('[') - value.IndexOf(']')) == 1)
//                    return false;
//                if (value.IndexOf('"') > -1 && SubstringCount(value.Trim(), "\"") % 2 == 1)
//                    return false;

//                return true;
//            }

//            return false;
//        }
//        int SubstringCount(string originalString, string subString)
//        {
//            string strReplaced = originalString.Replace(subString, "");
//            return (originalString.Length - strReplaced.Length) / subString.Length;
//        }
//        bool CheckArrayNumber(string[] arrary)
//        {
//            bool bResult = true;
//            if (arrary != null && arrary.Length > 0)
//            {
//                foreach (string a in arrary)
//                {
//                    int i;
//                    bResult = int.TryParse(a, out i);
//                    if (bResult)
//                    {

//                    }
//                    else
//                    {
//                        break;
//                    }
//                }
//            }
//            return bResult;
//        }
//        bool CheckArrayGuid(string[] arrary)
//        {
//            bool bResult = true;
//            if (arrary != null && arrary.Length > 0)
//            {
//                foreach (string a in arrary)
//                {
//                    Guid i;
//                    bResult = Guid.TryParse(a, out i);
//                    if (bResult)
//                    {

//                    }
//                    else
//                    {
//                        break;
//                    }
//                }
//            }
//            return bResult;
//        }

//        #region smart trigger 校验
//        ErrorInfo CheckSmartTriggerValidation(SmartTriggerConditions conditions)
//        {
//            ErrorInfo errorInfo = new ErrorInfo() { Code = 1 };

//            if (conditions == null) return errorInfo;
//            //if (conditions.When == null || !Enum.IsDefined(typeof(EnumConditionWhen), conditions.When))
//            //    return false;

//            if (conditions.When == EnumConditionWhen.expression && string.IsNullOrWhiteSpace(conditions.Expression))
//            {
//                return APIHelper.GetErrorMessageByCode(53202);
//            }
//            if (conditions.When == EnumConditionWhen.expression)
//            {
//                if (!checkExpression(conditions))
//                {
//                    errorInfo = APIHelper.GetErrorMessageByCode(53203);
//                    errorInfo.Message = string.Format(errorInfo.Message, conditions.Expression);
//                    return errorInfo;
//                };
//            }

//            if (conditions.Items != null && conditions.Items.Count != 0)
//            {
//                foreach (Com.Comm100.Public.Bot.SmartTriggerCondition condition in conditions.Items)
//                {


//                    if (condition.Expression == EnumConditionExpression.moreThan || condition.Expression == EnumConditionExpression.lessThan)
//                    {
//                        int result = 0;
//                        foreach (string item in condition.Items)
//                        {

//                            if (!int.TryParse(item, out result))
//                            {
//                                errorInfo = APIHelper.GetErrorMessageByCode(53211);
//                                errorInfo.Message = string.Format(errorInfo.Message, item);
//                                return errorInfo;
//                            }
//                            if (result < 0)
//                            {
//                                errorInfo = APIHelper.GetErrorMessageByCode(53211);
//                                errorInfo.Message = string.Format(errorInfo.Message, item);
//                                return errorInfo;
//                            }
//                        }

//                    }
//                    else
//                    {
//                        if (condition.Items != null && condition.Items.Count != 0)
//                        {
//                            if (string.Join("", condition.Items).Length > 2048)
//                            {
//                                return APIHelper.GetErrorMessageByCode(53223);
//                            }
//                        }
//                    }
//                }

//                return checkConditions(conditions.Items);

//            }


//            return errorInfo;

//        }
//        bool checkExpression(SmartTriggerConditions conditions)
//        {
//            string expression = conditions.Expression.ToLower().Replace("(", "").Replace(")", "").Replace("and", "").Replace("or", "").Replace(" ", "").Trim();
//            for (int i = 0; i < conditions.Items.Count; i++)
//            {
//                expression = expression.Replace((i + 1).ToString(), "");
//            }
//            if (!string.IsNullOrWhiteSpace(expression))
//                return false;

//            string express = conditions.Expression.ToLower();
//            express = express.Trim().Replace("and", "*").Replace("or", "+");
//            for (int i = 0; i < conditions.Items.Count; i++)
//            {
//                express = express.Replace((i + 1).ToString(), "0");
//            }
//            try
//            {
//                object result = (new System.Data.DataTable().Compute(express, null));
//            }

//            catch (Exception ex)
//            {
//                return false;
//            }


//            return true;
//        }
//        ErrorInfo checkConditions(List<Com.Comm100.Public.Bot.SmartTriggerCondition> conditions)
//        {
//            ErrorInfo errorInfo = new ErrorInfo() { Code = 1 };
//            int index = -1;
//            foreach (SmartTriggerCondition aCondtion in conditions)
//            {
//                index++;
//                if (aCondtion.Variable.StartsWith("pre_CustomField_") || aCondtion.Variable.StartsWith("customVariable_"))
//                    continue;
//                //{
//                //    if (aCondtion.Expression == EnumConditionExpression.lessThan || aCondtion.Expression == EnumConditionExpression.moreThan)
//                //    {
//                //        errorInfo = APIHelper.GetErrorMessageByCode(53213);
//                //        errorInfo.Message = string.Format(errorInfo.Message, aCondtion.Variable, aCondtion.Expression.ToString(), index);
//                //        return errorInfo;

//                //    }
//                //    else
//                //        continue;
//                //}

//                SmartTriggerConditionsAppService.Condition condition = SmartTriggerConditionsAppService.cds.Find(r => r.Valiable == aCondtion.Variable);
//                if (condition == null)
//                {
//                    errorInfo = APIHelper.GetErrorMessageByCode(53212);
//                    errorInfo.Message = string.Format(errorInfo.Message, aCondtion.Variable);
//                    return errorInfo;
//                };
//                if (!condition.Check((EnumConditionExpression)aCondtion.Expression))
//                {
//                    errorInfo = APIHelper.GetErrorMessageByCode(53213);
//                    errorInfo.Message = string.Format(errorInfo.Message, aCondtion.Variable, aCondtion.Expression.ToString(), index);
//                    return errorInfo;
//                };

//                //int itemIndex = -1;
//                //if (!condition.CheckValue(aCondtion.Items,out itemIndex))
//                //{
//                //    errorInfo = APIHelper.GetErrorMessageByCode(53224);
//                //    errorInfo.Message = string.Format(errorInfo.Message,  index,itemIndex);
//                //    return errorInfo;
//                //}

//                if (aCondtion.Items == null || aCondtion.Items.Count == 0 || aCondtion.Items.Exists(r => string.IsNullOrWhiteSpace(r)))
//                {
//                    errorInfo = APIHelper.GetErrorMessageByCode(53218);
//                    errorInfo.Message = string.Format(errorInfo.Message, index);
//                    return errorInfo;

//                }


//            }

//            return errorInfo;
//        }
//        ErrorInfo CheckSmartTriggerActionsValidation(IList<Com.Comm100.Public.Bot.SmartTriggerAction> actions)
//        {
//            ErrorInfo errorInfo = new ErrorInfo() { Code = 1 };

//            if (actions != null)
//            {

//                if (actions.Count(r => r.Type == Com.Comm100.Public.Enum.EnumActionType.changeAssignee) > 1)
//                    return APIHelper.GetErrorMessageByCode(53219);
//                if (actions.Count(r => r.Type == Com.Comm100.Public.Enum.EnumActionType.monitor) > 1)
//                    return APIHelper.GetErrorMessageByCode(53219);
//                if (actions.Count(r => r.Type == Com.Comm100.Public.Enum.EnumActionType.notification) > 1)
//                    return APIHelper.GetErrorMessageByCode(53219);
//                if (actions.Count(r => r.Type == Com.Comm100.Public.Enum.EnumActionType.segment) > 1)
//                    return APIHelper.GetErrorMessageByCode(53219);
//                if (actions.Count(r => r.Type == Com.Comm100.Public.Enum.EnumActionType.transfer) > 1)
//                    return APIHelper.GetErrorMessageByCode(53219);

//                foreach (Com.Comm100.Public.Bot.SmartTriggerAction item in actions)
//                {
//                    if ((item.Type == Com.Comm100.Public.Enum.EnumActionType.transfer || item.Type == Com.Comm100.Public.Enum.EnumActionType.changeAssignee) && string.IsNullOrWhiteSpace(item.AgentOfflineMessage))
//                        return APIHelper.GetErrorMessageByCode(53220);

//                    switch (item.Type)
//                    {
//                        case Com.Comm100.Public.Enum.EnumActionType.segment:
//                            if (item.Target.VisitorSegmentId == Guid.Empty)
//                                return APIHelper.GetErrorMessageByCode(53207);
//                            break;
//                        case Com.Comm100.Public.Enum.EnumActionType.transfer:
//                        case Com.Comm100.Public.Enum.EnumActionType.monitor:
//                        case Com.Comm100.Public.Enum.EnumActionType.changeAssignee:

//                            if (item.Target.Type == Com.Comm100.Public.Enum.EnumTargetType.agent)
//                            {
//                                if (item.Target.Agents == null || item.Target.Agents.Count == 0 || item.Target.Agents.Count > 1 || item.Target.Agents.ToList().Exists(r => r == Guid.Empty))
//                                {
//                                    errorInfo = APIHelper.GetErrorMessageByCode(53208);
//                                    errorInfo.Message = string.Format(errorInfo.Message, item.Type.ToString(), Com.Comm100.Public.Enum.EnumTargetType.agent.ToString());
//                                    return errorInfo;
//                                }
//                            }
//                            else if (item.Target.Type == Com.Comm100.Public.Enum.EnumTargetType.department)
//                            {
//                                if (item.Target.Departments == null || item.Target.Departments.Count == 0 || item.Target.Departments.Count > 1 || item.Target.Departments.ToList().Exists(r => r == Guid.Empty))
//                                {
//                                    errorInfo = APIHelper.GetErrorMessageByCode(53208);
//                                    errorInfo.Message = string.Format(errorInfo.Message, item.Type.ToString(), Com.Comm100.Public.Enum.EnumTargetType.department.ToString());
//                                    return errorInfo;
//                                }
//                            }
//                            else
//                            {
//                                errorInfo = APIHelper.GetErrorMessageByCode(53222);
//                                errorInfo.Message = string.Format(errorInfo.Message, item.Type.ToString(), Com.Comm100.Public.Enum.EnumTargetType.department.ToString());
//                                return errorInfo;
//                            }

//                            break;
//                            //case Com.Comm100.Public.Enum.EnumActionType.notification:
//                            //    if (item.Target.Type == Com.Comm100.Public.Enum.EnumTargetType.agent)
//                            //    {
//                            //        if (item.Target.Agents == null || item.Target.Agents.Count == 0 || item.Target.Agents.ToList().Exists(r => r < 1))
//                            //        {
//                            //            errorInfo = APIHelper.GetErrorMessageByCode(53215);
//                            //            errorInfo.Message = string.Format(errorInfo.Message, Com.Comm100.Public.Enum.EnumTargetType.agent.ToString());
//                            //            return errorInfo;
//                            //        }
//                            //    }
//                            //    else
//                            //    {
//                            //        if (item.Target.Departments == null || item.Target.Departments.Count == 0 || item.Target.Departments.ToList().Exists(r => r < 1))
//                            //        {
//                            //            errorInfo = APIHelper.GetErrorMessageByCode(53215);
//                            //            errorInfo.Message = string.Format(errorInfo.Message, Com.Comm100.Public.Enum.EnumTargetType.department.ToString());
//                            //            return errorInfo;
//                            //        }
//                            //    }
//                            //    break;
//                    }

//                }


//                if (actions.ToList().FindIndex(r => r.Type == Com.Comm100.Public.Enum.EnumActionType.monitor && r.IsEnabled.GetValueOrDefault()) > -1 && actions.ToList().FindIndex(r => r.Type == Com.Comm100.Public.Enum.EnumActionType.transfer && r.IsEnabled.GetValueOrDefault()) > -1)
//                    return APIHelper.GetErrorMessageByCode(53214);
//            }



//            return errorInfo;
//        }
//        #endregion

//        #region quick replays 校验
//        int CheckQuickReplyItemValidation(BotQuickReplyTypeEx quickReply)
//        {
//            if (quickReply != null && quickReply.QuickReplyItems != null && quickReply.QuickReplyItems.Length > 0)
//            {
//                if (quickReply.QuickReplyItems.Length > 0 /*&& quickReply.QuickReplyItems.Length < 11*/)
//                {
//                    if (quickReply.QuickReplyItems.Where(o => o.Type != BotQuickReplyItemTypeType.contactAgent && o.Type != BotQuickReplyItemTypeType.goToIntent).Count() > 0)
//                        return 54207;
//                    if (quickReply.QuickReplyItems.Where(o => o.Type == BotQuickReplyItemTypeType.contactAgent).Count() > 1)
//                        return 54203;
//                    if (quickReply.QuickReplyItems.Any(a => a.Type == BotQuickReplyItemTypeType.goToIntent && a.ItemName.Length > 1280))
//                        return 54209;
//                    if (quickReply.QuickReplyItems.Any(a => a.Type == BotQuickReplyItemTypeType.goToIntent && string.IsNullOrEmpty(a.ItemName)))
//                        return 54204;
//                }
//                //else
//                //    return 54202;
//            }
//            return 1;
//        }
//        #endregion

//        #region Intent 校验
//        private ErrorInfo IntentValidation(Intent intent, bool isSupportComplex, BotImportDataEx botImportDataEx)
//        {
//            if (intent == null)
//                return APIHelper.GetErrorMessageByCode(50001);
//            if (intent.Questions == null || intent.Questions.Count <= 0)
//                return APIHelper.GetErrorMessageByCode(51207);
//            if (intent.Answer == null || intent.Answer.Count <= 0)
//                return APIHelper.GetErrorMessageByCode(51369, new object[] { intent.Name });
//            if (intent.Answer.All(a => a.Value == null || a.Value.Responses == null || a.Value.Responses.Count <= 0))
//                return APIHelper.GetErrorMessageByCode(51371);
//            if (string.IsNullOrWhiteSpace(intent.Name))
//                return APIHelper.GetErrorMessageByCode(51209);
//            if (intent.Name.Length > 100)
//                return APIHelper.GetErrorMessageByCode(51210);
//            if (intent.Name.Equals("default", StringComparison.InvariantCultureIgnoreCase))
//                return APIHelper.GetErrorMessageByCode(51211);

//            Dictionary<Guid, List<string>> valData = new Dictionary<Guid, List<string>>();
//            string regexStr = @"^(?![0-9_-])[a-zA-Z0-9_-]{1,30}$";
//            if (intent.Questions != null && intent.Questions.Count > 0)
//            {
//                if (intent.Questions.GroupBy(g => g.Text.Trim()).Any(a => a.Count() > 1))
//                    return APIHelper.GetErrorMessageByCode(51350);
//                if (intent.Questions.Count > 2000)
//                    return APIHelper.GetErrorMessageByCode(51254);
//                for (int i = 0; i < intent.Questions.Count; i++)
//                {
//                    if (string.IsNullOrWhiteSpace(intent.Questions[i].Text)) return APIHelper.GetErrorMessageByCode(51353);
//                    if (intent.Questions[i].Text.Length > 768) return APIHelper.GetErrorMessageByCode(51255);
//                    if (intent.Questions[i].EntityLabels == null || intent.Questions[i].EntityLabels.Count <= 0) continue;
//                    List<string> labels = new List<string>();
//                    List<Tuple<int?, int?>> positions = new List<Tuple<int?, int?>>();
//                    foreach (var item in intent.Questions[i].EntityLabels)
//                    {
//                        if (string.IsNullOrWhiteSpace(item.Label))
//                            return APIHelper.GetErrorMessageByCode(51256);
//                        if (item.Label.Length > 30)
//                            return APIHelper.GetErrorMessageByCode(51257);
//                        if (item.Label.Trim().EndsWith("_") || item.Label.Trim().EndsWith("-")
//                            || item.Label.Trim().StartsWith("_") || item.Label.Trim().StartsWith("-") ||
//                            !Regex.IsMatch(item.Label, regexStr))
//                            return APIHelper.GetErrorMessageByCode(51258);
//                        if (item.StartPos > item.EndPos)
//                            return APIHelper.GetErrorMessageByCode(51260);
//                        int length = intent.Questions[i].Text.Length;

//                        if (item.StartPos < 0)
//                            return APIHelper.GetErrorMessageByCode(51367);
//                        if (item.EndPos < 0)
//                            return APIHelper.GetErrorMessageByCode(51368);

//                        if (item.StartPos >= length)
//                            return APIHelper.GetErrorMessageByCode(51335, new object[] { item.StartPos, length });
//                        if (item.EndPos >= length)
//                            return APIHelper.GetErrorMessageByCode(51336, new object[] { item.EndPos, length });
//                        if (labels.Contains(item.Label))
//                            return APIHelper.GetErrorMessageByCode(51327, new object[] { item.Label });
//                        else
//                            labels.Add(item.Label);
//                        foreach (var key in valData.Keys)
//                        {
//                            if (valData[key].Contains(item.Label) && item.EntityId != key)
//                                return APIHelper.GetErrorMessageByCode(51330, new object[] { item.Label, item.EntityId });
//                        }
//                        if (valData.Keys.Contains(item.EntityId))
//                            valData[item.EntityId].Add(item.Label);
//                        else
//                            valData.Add(item.EntityId, new List<string>() { item.Label });
//                        foreach (var pos in positions)
//                        {
//                            if (item.StartPos >= pos.Item1 && item.StartPos <= pos.Item2)
//                                return APIHelper.GetErrorMessageByCode(51328, new object[] { item.StartPos, pos.Item1, pos.Item2 });
//                            if (item.EndPos >= pos.Item1 && item.EndPos <= pos.Item2)
//                                return APIHelper.GetErrorMessageByCode(51329, new object[] { item.EndPos, pos.Item1, pos.Item2 });
//                        }
//                        positions.Add(new Tuple<int?, int?>(item.StartPos, item.EndPos));
//                    }
//                }
//            }
//            //1. via prompts 时，promot数量大于0,小于等于30，长度最长为768
//            //2. via form 时，字段数量大于0，entity 长度大于0，entityLabel 长度在0-30之间
//            //option个数小于等于10，字段长度小于20
//            //entity name  / entitylabel 只能允许输入 A-Z ,a-z ,0-9, _ - 之内的字符,长度在30以内。
//            //button上的文字最长20
//            if (intent.IfRequireDetailInfo && (intent.EntityCollectionType == null
//                || (intent.EntityCollectionType != EnumEntityCollectionType.form
//                && intent.EntityCollectionType != EnumEntityCollectionType.prompt)))
//                return APIHelper.GetErrorMessageByCode(51261);
//            //if (intent.IfRequireDetailInfo && (intent.Questions.All(a => a.EntityLabels == null || a.EntityLabels.Count <= 0)))
//            //    return APIHelper.GetErrorMessageByCode(51354); 2019.6.24 收集信息不是必须有Entity
//            if (intent.IfRequireDetailInfo && intent.EntityCollectionType == EnumEntityCollectionType.prompt
//                && (intent.EntityCollectionPrompts == null || intent.EntityCollectionPrompts.Count <= 0)) return APIHelper.GetErrorMessageByCode(51262);
//            if (intent.IfRequireDetailInfo && intent.EntityCollectionType == EnumEntityCollectionType.form
//                && (intent.EntityCollectionForm == null || intent.EntityCollectionForm.FormFields == null || intent.EntityCollectionForm.FormFields.Count <= 0))
//                return APIHelper.GetErrorMessageByCode(51263);
//            if (intent.IfRequireDetailInfo && intent.EntityCollectionType == EnumEntityCollectionType.form && intent.EntityCollectionForm != null
//               && string.IsNullOrWhiteSpace(intent.EntityCollectionForm.FormMessage))
//                return APIHelper.GetErrorMessageByCode(51264);
//            if (intent.IfRequireDetailInfo && intent.EntityCollectionType == EnumEntityCollectionType.form && intent.EntityCollectionForm != null
//                && string.IsNullOrWhiteSpace(intent.EntityCollectionForm.FormTitle))
//                return APIHelper.GetErrorMessageByCode(51265);
//            if (intent.IfRequireDetailInfo && intent.EntityCollectionType == EnumEntityCollectionType.form && intent.EntityCollectionForm != null
//                 && intent.EntityCollectionForm.FormMessage.Length > 1280)
//                return APIHelper.GetErrorMessageByCode(51266);
//            if (intent.IfRequireDetailInfo && intent.EntityCollectionType == EnumEntityCollectionType.form && intent.EntityCollectionForm != null
//                && intent.EntityCollectionForm.FormTitle.Length > 20)
//                return APIHelper.GetErrorMessageByCode(51267);
//            if (intent.IfRequireDetailInfo && intent.EntityCollectionType == EnumEntityCollectionType.form)
//            {
//                var errorInfo = ValidateEntityCollectionFormFields(intent.EntityCollectionForm.FormFields, valData, regexStr);
//                if (errorInfo != null) return errorInfo;
//            }
//            if (intent.IfRequireDetailInfo && intent.EntityCollectionType == EnumEntityCollectionType.prompt)
//            {
//                var errorInfo = ValidateEntityCollectionPrompts(intent.EntityCollectionPrompts, valData, regexStr);
//                if (errorInfo != null) return errorInfo;
//            }
//            List<string> channels = new List<string>();
//            foreach (var key in intent.Answer.Keys)
//            {
//                string channel = key.ToLower();
//                if (channels.Contains(channel))
//                    return APIHelper.GetErrorMessageByCode(51339);
//                channels.Add(channel);
//                if (channel == ConstChannelType.Default || channel == ConstChannelType.Livechat || channel == ConstChannelType.Facebook || channel == ConstChannelType.Twitter)
//                    continue;
//                return APIHelper.GetErrorMessageByCode(51340);
//            }
//            //if(!channels.Contains(ConstChannelType.Default))
//            //    return APIHelper.GetErrorMessageByCode(51355);
//            foreach (var key in intent.Answer.Keys)
//            {
//                //if (key.Equals(ConstChannelType.Default, StringComparison.InvariantCultureIgnoreCase))
//                //{
//                //    if (intent.Answer[key].Responses == null || intent.Answer[key].Responses.Count <= 0)
//                //        return APIHelper.GetErrorMessageByCode(51355);
//                //}
//                ErrorInfo error = AnswerValidation(intent.Answer[key], key, isSupportComplex, botImportDataEx);
//                if (error != null) return error;
//            }
//            return null;
//        }
//        private ErrorInfo AnswerValidation(AnswerSubItem subItem, string channelType, bool isSupportComplex, BotImportDataEx botImportDataEx)
//        {
//            List<EnumOpenIn?> openInLst = new List<EnumOpenIn?>();
//            openInLst.Add(EnumOpenIn.currentWindow);
//            openInLst.Add(EnumOpenIn.newWindow);
//            openInLst.Add(EnumOpenIn.sideWindow);
//            //允许response为空，response为空时认为该channel不存在数据
//            //response不为空时，对数据做校验
//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 10)
//                return APIHelper.GetErrorMessageByCode(51212);
//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 0
//               && subItem.IfNeedSignIn && subItem.AnswerSignInSettings == null)
//                return APIHelper.GetErrorMessageByCode(51213);
//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 0
//               && subItem.IfNeedSignIn && subItem.AnswerSignInSettings != null
//               && string.IsNullOrWhiteSpace(subItem.AnswerSignInSettings.SignInLinkText))
//                return APIHelper.GetErrorMessageByCode(51214);
//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 0
//              && subItem.IfNeedSignIn && subItem.AnswerSignInSettings != null
//              && string.IsNullOrWhiteSpace(subItem.AnswerSignInSettings.SignInMessage))
//                return APIHelper.GetErrorMessageByCode(51215);

//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 0
//              && subItem.IfNeedSignIn && subItem.AnswerSignInSettings != null
//              && !subItem.AnswerSignInSettings.IsSSO
//              && string.IsNullOrWhiteSpace(subItem.AnswerSignInSettings.SignInURL))
//                return APIHelper.GetErrorMessageByCode(51216);

//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 0
//            && subItem.IfNeedSignIn && subItem.AnswerSignInSettings != null
//            && !string.IsNullOrWhiteSpace(subItem.AnswerSignInSettings.CustomVariable)
//            && subItem.AnswerSignInSettings.CustomVariable.Length > 128)
//                return APIHelper.GetErrorMessageByCode(51347);

//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 0
//                && subItem.IfNeedSignIn && subItem.AnswerSignInSettings != null
//                && subItem.AnswerSignInSettings.SignInLinkText.Length > 128)
//                return APIHelper.GetErrorMessageByCode(51217);
//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 0
//                && subItem.IfNeedSignIn && subItem.AnswerSignInSettings != null && subItem.AnswerSignInSettings.SignInMessage.Length > 1280)
//                return APIHelper.GetErrorMessageByCode(51218);
//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 0
//                && subItem.IfNeedSignIn && subItem.AnswerSignInSettings != null
//                && !string.IsNullOrWhiteSpace(subItem.AnswerSignInSettings.SignInURL)
//                && subItem.AnswerSignInSettings.SignInURL.Length > 1280)
//                return APIHelper.GetErrorMessageByCode(51219);
//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 0
//                && subItem.IfNeedSignIn && subItem.AnswerSignInSettings != null
//                && !subItem.AnswerSignInSettings.IsSSO && !openInLst.Contains(subItem.AnswerSignInSettings.OpenIn))
//                return APIHelper.GetErrorMessageByCode(51220);

//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 0
//                && subItem.IfNeedSignIn && subItem.AnswerSignInSettings != null
//                && !subItem.AnswerSignInSettings.IsSSO
//                && string.IsNullOrWhiteSpace(subItem.AnswerSignInSettings.CustomVariable))
//                return APIHelper.GetErrorMessageByCode(51356);

//            var quickResponses = subItem.Responses.Where(w => w.type == EnumAnswerType.quickReply);
//            if (quickResponses != null && quickResponses.Count() > 1)
//                return APIHelper.GetErrorMessageByCode(51323);

//            if (quickResponses != null && quickResponses.Count() == 1)
//            {
//                Response quickResponse = quickResponses.FirstOrDefault();
//                subItem.Responses.Remove(quickResponse);
//                subItem.Responses.Add(quickResponse);
//            }
//            if (isSupportComplex)
//            {
//                var complexResponses = subItem.Responses.Where(w => w.type == EnumAnswerType.complex);
//                if (complexResponses != null && complexResponses.Count() > 1)
//                    return APIHelper.GetErrorMessageByCode(51345);
//            }
//            if (subItem != null && subItem.Responses != null && subItem.Responses.Count > 0)
//            {
//                foreach (var item in subItem.Responses)
//                {
//                    ErrorInfo error = ResponseValidation(item, channelType, botImportDataEx, isSupportComplex);
//                    if (error != null) return error;
//                }
//            }
//            return null;
//        }
//        private ErrorInfo ValidateEntityCollectionFormFields(List<EntityCollectionFormField> fields,
//            Dictionary<Guid, List<string>> labels, string regexStr)
//        {
//            List<string> existLabel = new List<string>();
//            List<Com.Comm100.Public.Enum.EnumFieldType?> fieldTypes = new List<Com.Comm100.Public.Enum.EnumFieldType?>();
//            fieldTypes.Add(Com.Comm100.Public.Enum.EnumFieldType.text);
//            fieldTypes.Add(Com.Comm100.Public.Enum.EnumFieldType.textArea);
//            fieldTypes.Add(Com.Comm100.Public.Enum.EnumFieldType.radio);
//            fieldTypes.Add(Com.Comm100.Public.Enum.EnumFieldType.checkBox);
//            fieldTypes.Add(Com.Comm100.Public.Enum.EnumFieldType.checkBoxList);
//            fieldTypes.Add(Com.Comm100.Public.Enum.EnumFieldType.dropDownList);
//            foreach (var item in fields)
//            {
//                if (!string.IsNullOrWhiteSpace(item.Label))
//                {
//                    //2019.6.24 收集信息不是必须有Entity
//                    //if (string.IsNullOrWhiteSpace(item.Label))
//                    //    return APIHelper.GetErrorMessageByCode(51268);
//                    if (item.Label.Length > 30)
//                        return APIHelper.GetErrorMessageByCode(51269);
//                    if (item.Label.Trim().EndsWith("_") || item.Label.Trim().EndsWith("-")
//                    || item.Label.Trim().StartsWith("_") || item.Label.Trim().StartsWith("-") ||
//                    !Regex.IsMatch(item.Label, regexStr))
//                        return APIHelper.GetErrorMessageByCode(51270);

//                    if (!labels[item.EntityId].Contains(item.Label))
//                        return APIHelper.GetErrorMessageByCode(51333, new object[] { item.EntityId, item.Label });
//                    if (existLabel.Contains(item.Label))
//                    {
//                        return APIHelper.GetErrorMessageByCode(51338, new object[] { item.Label });
//                    }
//                    else
//                    {
//                        existLabel.Add(item.Label);
//                    }
//                }

//                if (item.Options != null)
//                {
//                    if (item.Options.Count > 10)
//                        return APIHelper.GetErrorMessageByCode(51272);
//                    foreach (var option in item.Options)
//                    {
//                        if (string.IsNullOrWhiteSpace(option))
//                            return APIHelper.GetErrorMessageByCode(51273);
//                        if (option.Length > 100)
//                            return APIHelper.GetErrorMessageByCode(51274);
//                    }
//                }
//                if (!fieldTypes.Contains(item.FieldType))
//                    return APIHelper.GetErrorMessageByCode(51275);
//                if (string.IsNullOrWhiteSpace(item.FieldName))
//                    return APIHelper.GetErrorMessageByCode(51276);
//                if (item.FieldName.Length > 128)
//                    return APIHelper.GetErrorMessageByCode(51277);
//            }
//            return null;
//        }
//        private ErrorInfo ValidateEntityCollectionPrompts(List<EntityCollectionPrompt> entityCollectionPrompts,
//            Dictionary<Guid, List<string>> labels, string regexStr)
//        {
//            List<string> existLabel = new List<string>();
//            foreach (var item in entityCollectionPrompts)
//            {
//                if (string.IsNullOrWhiteSpace(item.Label))
//                    return APIHelper.GetErrorMessageByCode(51278);
//                if (item.Label.Length > 30)
//                    return APIHelper.GetErrorMessageByCode(51279);
//                if (item.Label.Trim().EndsWith("_") || item.Label.Trim().EndsWith("-")
//                  || item.Label.Trim().StartsWith("_") || item.Label.Trim().StartsWith("-") ||
//                  !Regex.IsMatch(item.Label, regexStr))
//                    return APIHelper.GetErrorMessageByCode(51280);

//                if (item.Options != null)
//                {
//                    //2016.6.26 取消个数限制
//                    //if (item.Options.Count > 10)
//                    //    return APIHelper.GetErrorMessageByCode(51282);

//                    foreach (var option in item.Options)
//                    {
//                        if (string.IsNullOrWhiteSpace(option))
//                            return APIHelper.GetErrorMessageByCode(51283);
//                        if (option.Length > 20)
//                            return APIHelper.GetErrorMessageByCode(51284);
//                    }
//                }
//                if (item.Questions == null || item.Questions.Count <= 0)
//                    return APIHelper.GetErrorMessageByCode(51285);
//                if (item.Questions.Count > 30)
//                    return APIHelper.GetErrorMessageByCode(51286);
//                foreach (var question in item.Questions)
//                {
//                    if (string.IsNullOrWhiteSpace(question))
//                        return APIHelper.GetErrorMessageByCode(51287);
//                    if (question.Length > 768)
//                        return APIHelper.GetErrorMessageByCode(51288);
//                }
//                if (string.Join(CommonCharacter.Split, item.Questions).Length > 4000)
//                    return APIHelper.GetErrorMessageByCode(51365);
//            }
//            return null;
//        }
//        private ErrorInfo ResponseValidation(Response response, string channelType, BotImportDataEx botImportDataEx, bool isSupportComplex = false)
//        {
//            string channel = channelType.ToLower();
//            if (channel == ConstChannelType.Default)
//            {
//                if (response.type != Com.Comm100.Public.Enum.EnumAnswerType.text
//                    && response.type != Com.Comm100.Public.Enum.EnumAnswerType.button
//                    && response.type != Com.Comm100.Public.Enum.EnumAnswerType.quickReply)
//                {
//                    return APIHelper.GetErrorMessageByCode(51351);
//                }
//            }
//            List<string> openInLst = new List<string>();
//            openInLst.Add(Com.Comm100.Public.Enum.EnumOpenIn.currentWindow.ToString());
//            openInLst.Add(Com.Comm100.Public.Enum.EnumOpenIn.newWindow.ToString());
//            openInLst.Add(Com.Comm100.Public.Enum.EnumOpenIn.sideWindow.ToString());
//            List<string> openStyleLst = new List<string>();
//            openStyleLst.Add(Com.Comm100.Public.Enum.EnumOpenStyle.compact.ToString());
//            openStyleLst.Add(Com.Comm100.Public.Enum.EnumOpenStyle.full.ToString());
//            openStyleLst.Add(Com.Comm100.Public.Enum.EnumOpenStyle.tall.ToString());
//            List<string> typeLst = new List<string>();
//            typeLst.Add(Com.Comm100.Public.Enum.EnumButtonType.goToIntent.ToString());
//            typeLst.Add(Com.Comm100.Public.Enum.EnumButtonType.link.ToString());
//            typeLst.Add(Com.Comm100.Public.Enum.EnumButtonType.webView.ToString());

//            switch (response.type)
//            {
//                case Com.Comm100.Public.Enum.EnumAnswerType.text:
//                    TextResponse textResponse = response.content as TextResponse;
//                    if (textResponse == null || textResponse.texts == null || textResponse.texts.Length <= 0)
//                        return APIHelper.GetErrorMessageByCode(51221);
//                    else if (textResponse.texts.Length > 10)
//                        return APIHelper.GetErrorMessageByCode(51222);
//                    string totalText = string.Join(CommonCharacter.Split, textResponse.texts);
//                    if (totalText.Length > 4000)
//                        return APIHelper.GetErrorMessageByCode(51364);
//                    else if (textResponse.texts.Any(a => string.IsNullOrWhiteSpace(a)))
//                        return APIHelper.GetErrorMessageByCode(51223);
//                    if (channel != ConstChannelType.Livechat)
//                    {
//                        if (textResponse.texts.Any(a => a.Contains("href=\"intent") || a.Contains("href='intent") || a.Contains("data-intent")))
//                            return APIHelper.GetErrorMessageByCode(51363);
//                    }
//                    break;
//                case Com.Comm100.Public.Enum.EnumAnswerType.image:
//                    var imageResponse = response.content as ImageResponse;
//                    if (imageResponse == null)
//                        return APIHelper.GetErrorMessageByCode(51224);
//                    if (string.IsNullOrWhiteSpace(imageResponse.name))
//                        return APIHelper.GetErrorMessageByCode(51225);
//                    if (string.IsNullOrWhiteSpace(imageResponse.url))
//                        return APIHelper.GetErrorMessageByCode(51226);
//                    if (imageResponse.name.Length > 260)
//                        return APIHelper.GetErrorMessageByCode(51227);
//                    if (imageResponse.url.Length > 1280)
//                        return APIHelper.GetErrorMessageByCode(51228);
//                    break;
//                case Com.Comm100.Public.Enum.EnumAnswerType.video:
//                    var videoResponse = response.content as UrlResponse;
//                    if (videoResponse == null)
//                        return APIHelper.GetErrorMessageByCode(51229);
//                    if (string.IsNullOrWhiteSpace(videoResponse.url))
//                        return APIHelper.GetErrorMessageByCode(51230);
//                    if (videoResponse.url.Length > 1280)
//                        return APIHelper.GetErrorMessageByCode(51231);
//                    break;
//                case Com.Comm100.Public.Enum.EnumAnswerType.webhook:
//                    var webhookResponse = response.content as WebhookResponse;
//                    if (webhookResponse == null)
//                        return APIHelper.GetErrorMessageByCode(51232);
//                    if (string.IsNullOrWhiteSpace(webhookResponse.url))
//                        return APIHelper.GetErrorMessageByCode(51233);
//                    if (webhookResponse.url.Length > 1280)
//                        return APIHelper.GetErrorMessageByCode(51234);
//                    if (webhookResponse.headers != null && webhookResponse.headers.Count > 0)
//                    {
//                        if (webhookResponse.headers.Any(a => string.IsNullOrWhiteSpace(a.Key)))
//                        {
//                            return APIHelper.GetErrorMessageByCode(51381);
//                        }
//                        if (webhookResponse.headers.Any(a => !string.IsNullOrWhiteSpace(a.Key) && a.Key.Length > 4000))
//                        {
//                            return APIHelper.GetErrorMessageByCode(51384);
//                        }
//                        if (webhookResponse.headers.Any(a => string.IsNullOrWhiteSpace(a.Value)))
//                        {
//                            return APIHelper.GetErrorMessageByCode(51382);
//                        }
//                        if (webhookResponse.headers.Any(a => !string.IsNullOrWhiteSpace(a.Value) && a.Value.Length > 4000))
//                        {
//                            return APIHelper.GetErrorMessageByCode(51385);
//                        }
//                    }
//                    break;
//                case Com.Comm100.Public.Enum.EnumAnswerType.quickReply:
//                    var quickReplyResponse = response.content as ComplexQuickReplyResponse;
//                    if (quickReplyResponse == null)
//                    {
//                        return APIHelper.GetErrorMessageByCode(51235);
//                    }
//                    //2019.7.16 允许为空
//                    //if (string.IsNullOrWhiteSpace(quickReplyResponse.text))
//                    //    return APIHelper.GetErrorMessageByCode(51236);
//                    if (!string.IsNullOrWhiteSpace(quickReplyResponse.text) &&
//                        quickReplyResponse.text.Length > 1280)
//                        return APIHelper.GetErrorMessageByCode(51237);

//                    break;
//                case Com.Comm100.Public.Enum.EnumAnswerType.button:
//                    var buttonResponse = response.content as ButtonResponse;

//                    if (string.IsNullOrWhiteSpace(buttonResponse.text))
//                        return APIHelper.GetErrorMessageByCode(51240);
//                    if (buttonResponse.text.Length > 4000)
//                        return APIHelper.GetErrorMessageByCode(51241);
//                    if (buttonResponse.buttons == null || buttonResponse.buttons.Length <= 0)
//                        return APIHelper.GetErrorMessageByCode(51242);

//                    if (channel != ConstChannelType.Livechat)
//                    {//2019.6.26
//                        if (buttonResponse.buttons.Length > 3)
//                            return APIHelper.GetErrorMessageByCode(51243);
//                    }

//                    foreach (var item in buttonResponse.buttons)
//                    {
//                        if (item.type == Com.Comm100.Public.Enum.EnumButtonType.link
//                            && !openInLst.Contains(item.openIn.ToString())
//                            && channel == ConstChannelType.Livechat)
//                            return APIHelper.GetErrorMessageByCode(51244);
//                        if (item.type == Com.Comm100.Public.Enum.EnumButtonType.webView
//                            && !openStyleLst.Contains(item.openStyle.ToString())
//                            && (channel == ConstChannelType.Livechat || channel == ConstChannelType.Facebook))
//                            return APIHelper.GetErrorMessageByCode(51245);
//                        if (!typeLst.Contains(item.type.ToString()))
//                            return APIHelper.GetErrorMessageByCode(51246);
//                        if (string.IsNullOrWhiteSpace(item.text))
//                            return APIHelper.GetErrorMessageByCode(51247);

//                        if (channel == ConstChannelType.Livechat)
//                        {//2019.6.26
//                            if (item.text.Length > 128)
//                                return APIHelper.GetErrorMessageByCode(51377);
//                        }
//                        else
//                        {
//                            if (item.text.Length > 20)
//                                return APIHelper.GetErrorMessageByCode(51248);
//                        }

//                        if (item.type == Com.Comm100.Public.Enum.EnumButtonType.goToIntent && channel != ConstChannelType.Livechat && channel != ConstChannelType.Facebook)
//                            return APIHelper.GetErrorMessageByCode(51346);
//                        if ((item.type == Com.Comm100.Public.Enum.EnumButtonType.link || item.type == Com.Comm100.Public.Enum.EnumButtonType.webView) && string.IsNullOrWhiteSpace(item.linkUrl))
//                            return APIHelper.GetErrorMessageByCode(51252);
//                        if ((item.type == Com.Comm100.Public.Enum.EnumButtonType.link || item.type == Com.Comm100.Public.Enum.EnumButtonType.webView) && item.linkUrl.Length > 1280)
//                            return APIHelper.GetErrorMessageByCode(51253);
//                    }
//                    break;
//                case Com.Comm100.Public.Enum.EnumAnswerType.complex:
//                    if (isSupportComplex)
//                    {
//                        if (channelType != ConstChannelType.Livechat)
//                        {
//                            return APIHelper.GetErrorMessageByCode(51352);
//                        }
//                        var complexResponse = response.content as ComplexResponse;
//                        if (complexResponse == null)
//                            return APIHelper.GetErrorMessageByCode(51343);
//                        if (string.IsNullOrWhiteSpace(complexResponse.text))
//                            return APIHelper.GetErrorMessageByCode(51342);
//                    }
//                    else
//                    {
//                        return APIHelper.GetErrorMessageByCode(51344);
//                    }
//                    break;
//                default:
//                    return APIHelper.GetErrorMessageByCode(51341);
//            }
//            return null;
//        }
//        private bool CheckAnswerResponeLink(BotImportDataEx botImportDataEx, string content, Com.Comm100.Public.Enum.EnumAnswerType answerType)
//        {
//            bool valid = true;
//            if (answerType == Com.Comm100.Public.Enum.EnumAnswerType.text)
//            {
//                //可能里面包含 link gotoIntent 
//                if (!string.IsNullOrEmpty(content))
//                {
//                    content = System.Web.HttpUtility.HtmlDecode(content);
//                    List<BotIntentTypeEx> botIntentsList = botImportDataEx.Bot.Category.SelectMany(a => a.Intent).ToList();

//                    string pattern = "<a href=.*?>([^<]+?)</a>";
//                    bool ifMatch = Regex.IsMatch(content, pattern);
//                    if (ifMatch)
//                    {
//                        Regex regex = new Regex(pattern);
//                        MatchCollection matchCollection = regex.Matches(content);
//                        foreach (Match match in matchCollection)
//                        {
//                            string html = match.Groups[0].Value;
//                            string dataLinkType = Utils.GetTitleContent(html, "a", "data-linktype");
//                            if (dataLinkType == "1")
//                            {
//                                string intentname = Utils.GetTitleContent(html, "a", "data-intentname");
//                                if (!string.IsNullOrEmpty(intentname))
//                                {
//                                    //判断 intent 是否存在
//                                    BotIntentTypeEx botIntentFind = botIntentsList.FirstOrDefault(a => a.IntentName == intentname);
//                                    if (botIntentFind != null)
//                                    {
//                                    }
//                                    else
//                                    {
//                                        valid = false;
//                                        break;
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//            else if (answerType == Com.Comm100.Public.Enum.EnumAnswerType.complex)
//            {
//                //可能里面包含 link gotoIntent 
//                if (!string.IsNullOrEmpty(content))
//                {
//                    content = System.Web.HttpUtility.HtmlDecode(content);
//                    List<BotIntentTypeEx> botIntentsList = botImportDataEx.Bot.Category.SelectMany(a => a.Intent).ToList();

//                    string pattern = @"<a title=.*?>([^<]+?)</a>";
//                    bool ifMatch = Regex.IsMatch(content, pattern);
//                    if (ifMatch)
//                    {
//                        Regex reg = new Regex(pattern);
//                        MatchCollection matchCollection = reg.Matches(content);
//                        if (matchCollection != null && matchCollection.Count > 0)
//                        {
//                            foreach (Match match in matchCollection)
//                            {
//                                string html = match.Value;
//                                string dataLinkType = Utils.GetTitleContent(html, "a", "data-linktype");
//                                if (dataLinkType == "1")
//                                {
//                                    string intentName = Utils.GetTitleContent(html, "a", "data-intentname");
//                                    BotIntentTypeEx botIntentsFind = botIntentsList.FirstOrDefault(a => a.IntentName == intentName);
//                                    if (botIntentsFind != null)
//                                    {

//                                    }
//                                    else
//                                    {
//                                        string data = match.Groups[1].Value;
//                                        botIntentsFind = botIntentsList.FirstOrDefault(a => a.IntentName == data);
//                                    }

//                                    if (botIntentsFind != null)
//                                    {
//                                    }
//                                    else
//                                    {
//                                        valid = false;
//                                        break;
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//            return valid;
//        }
//        #endregion

//        private string CheckFile(string filePath)
//        {
//            string errorMsg = "";

//            string[] fileExtensions = new string[] { ".xml" };
//            if (File.Exists(filePath))
//            {
//                FileInfo fileInfo = new FileInfo(filePath);
//                string extension = fileInfo.Extension;
//                decimal fileSize = Math.Round(decimal.Divide(fileInfo.Length, 1024 * 1024), 2);

//                if (!fileExtensions.Contains(extension))
//                {
//                    errorMsg = "Invalid file type.";
//                }
//                else if (fileSize > 10)
//                {
//                    errorMsg = "The file size should be less than 10MB.";
//                }
//            }
//            else
//            {
//                errorMsg = "File not exist";
//            }

//            return errorMsg;
//        }
//        private string InitDataWithBotEngine(BotImportDataEx botImportData, Chatbot bot)
//        {
//            string errorMessage = "";
//            try
//            {
//                IBotApiService botApiService = _container.Resolve<IBotApiService>();
//                var botDto = Mapper.Map<BotDto>(bot);

//                List<IntentModelAggregate> intentModelAggregateList = botApiService.GetIntentList(botDto).Result;
//                List<EntityModelAggregate> entityModelAggregateList = botApiService.GetEntityList(botDto).Result;
//                SetIntentIdForBotImportData(intentModelAggregateList, botImportData, bot);
//                SetEntityIdForBotImportData(entityModelAggregateList, botImportData, bot);
//            }
//            catch (Exception e)
//            {
//                errorMessage = e.Message;
//                LogHelper.Error(JsonConvert.SerializeObject(e));
//            }
//            finally
//            {

//            }
//            return errorMessage;

//        }
//        private BotImportDataQueue GetImportDataQueue(Guid jobId, string fileName, Chatbot bot, out BackgroundJob backgroundJob)
//        {
//            backgroundJob = null;
//            BotImportDataQueue botImportDataQueue = null;

//            IBackgroundJobDomainService backgroundJobDomainService = _container.Resolve<IBackgroundJobDomainService>();

//            backgroundJob = backgroundJobDomainService.Get(jobId);

//            //string key = jobId.ToString();
//            //backgroundJob = Utils.GetMemoryCache<BackgroundJob>(key);

//            if (backgroundJob != null)
//            {
//                OperateEntity operateEntity = JsonConvert.DeserializeObject<OperateEntity>(backgroundJob.Content);
//                botImportDataQueue = JsonConvert.DeserializeObject<BotImportDataQueue>(Convert.ToString(operateEntity.Content));
//            }

//            if (botImportDataQueue == null)
//            {
//                botImportDataQueue = new BotImportDataQueue()
//                {
//                    ProcessState = EnumOperationStatus.Free,
//                    FileName = fileName,
//                    OperateType = EnumOperateType.importBot,
//                    OperationName = jobId.ToString(),
//                };

//                BotImportDataQueue newBotImportDataQueue = new BotImportDataQueue(botImportDataQueue);
//                newBotImportDataQueue.ProcessState = EnumOperationStatus.Occupy;
//                backgroundJob = CreateImportDataQueue(jobId, fileName, newBotImportDataQueue, bot);
//            }
//            else if (botImportDataQueue.ProcessState == EnumOperationStatus.Free)
//            {
//                BotImportDataQueue newBotImportDataQueue = new BotImportDataQueue(botImportDataQueue);
//                newBotImportDataQueue.ProcessState = EnumOperationStatus.Occupy;
//                SetImportDataQueue(jobId, fileName, newBotImportDataQueue, bot, backgroundJob);
//            }
//            return botImportDataQueue;
//        }
//        private BackgroundJob CreateImportDataQueue(Guid jobId, string fileName, BotImportDataQueue botImportDataQueue, Chatbot bot)
//        {        
//            OperateEntity operateEntity = new OperateEntity
//            {
//                SiteId = bot.SiteId,
//                BotId = bot.Id,
//                FilePath = fileName,
//                OperateType = EnumOperateType.importBot,
//                Content = botImportDataQueue,
//            };
//            BackgroundJob job = new BackgroundJob
//            {
//                Id = jobId,
//                SiteId = bot.SiteId,
//                BotId = bot.Id,
//                Type = EnumOperateType.importIntent,
//                Attachment = new byte[] { },
//                Content = JsonConvert.SerializeObject(operateEntity),
//                Status = botImportDataQueue.ProcessState,
//                CreatedTime = DateTime.UtcNow,
//            };

//            IBackgroundJobDomainService backgroundJobDomainService = _container.Resolve<IBackgroundJobDomainService>();

//            backgroundJobDomainService.Create(job);

//            //string key = jobId.ToString();
//            //Utils.SetMemoryCache(key, job);
//            return job;
//        }
//        private void SetImportDataQueue(Guid jobId, string fileName, BotImportDataQueue botImportDataQueue, Chatbot bot, BackgroundJob backgroundJob)
//        {
//            OperateEntity operateEntity = new OperateEntity
//            {
//                SiteId = bot.SiteId,
//                BotId = bot.Id,
//                FilePath = fileName,
//                OperateType = EnumOperateType.importBot,
//                Content = botImportDataQueue,
//            };
//            BackgroundJobUpdateBo job = new BackgroundJobUpdateBo
//            {
//                Id = jobId,
//                SiteId = bot.SiteId,
//                BotId = bot.Id,
//                Type = EnumOperateType.importBot,
//                Attachment = new byte[] { },
//                Content = JsonConvert.SerializeObject(operateEntity),
//                Status = botImportDataQueue.ProcessState,
//                CreatedTime = DateTime.UtcNow,
//            };
//            //string key = jobId.ToString();
//            //Utils.SetMemoryCache(key, job);
//            IBackgroundJobDomainService backgroundJobDomainService = _container.Resolve<IBackgroundJobDomainService>();
//            backgroundJobDomainService.Update(job);
//        }
//        #region 导出文件形式赋值
//        private void SetIntentIdForBotImportData(BotAggregate botAggregate, BotImportDataEx botImportData)
//        {
//            if (botAggregate != null && botAggregate.IntentModelList != null)
//            {
//                foreach (BotCategoryTypeEx category in botImportData.Bot.Category)
//                {
//                    foreach (BotIntentTypeEx botIntent in category.Intent)
//                    {
//                        string intentId = botAggregate.IntentModelList.FirstOrDefault(a => a.IntentName == botIntent.IntentName)?.Id;
//                        if (!string.IsNullOrEmpty(intentId))
//                        {
//                            botIntent.MappingToBotEngine = string.Format("{0}", intentId);
//                        }
//                        else
//                        {
//                            throw new Exception(string.Format("Cannot find an application version with the version."));
//                        }
//                    }
//                }
//            }
//            else
//            {
//                throw new Exception(string.Format("Cannot find an application version with the version."));
//            }
//        }
//        private void SetQuestionIdForBotImportData(BotAggregate botAggregate, BotImportDataEx botImportData)
//        {
//            if (botAggregate != null && botAggregate.IntentQuestionModelList != null)
//            {
//                foreach (BotCategoryTypeEx category in botImportData.Bot.Category)
//                {
//                    foreach (BotIntentTypeEx botIntent in category.Intent)
//                    {
//                        if (botIntent.Question != null)
//                        {
//                            foreach (BotIntentQuestionTypeEx botIntentQuestion in botIntent.Question)
//                            {
//                                IntentQuestionModel intentQuestionModel = botAggregate.IntentQuestionModelList.First(a => a.Question == botIntentQuestion.Content);
//                                string questionId = intentQuestionModel?.Id;

//                                if (questionId != null)
//                                {
//                                    botIntentQuestion.IdInBotEngine = questionId;
//                                }
//                                else
//                                {
//                                    throw new Exception(string.Format("Cannot find an application version with the version."));
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//            else
//            {
//                throw new Exception(string.Format("Cannot find an application version with the version."));
//            }

//        }
//        private void SetEntityIdForBotImportData(BotAggregate botAggregate, BotImportDataEx botImportData)
//        {
//            if (botAggregate != null && botAggregate.EntityModelList != null)
//            {
//                foreach (BotEntityTypeEx botEntity in botImportData.Bot.Entity)
//                {
//                    EntityModel entityModel = botAggregate.EntityModelList.FirstOrDefault(a => a.EntityName == botEntity.EntityName);
//                    string entityId = entityModel?.Id;
//                    if (!string.IsNullOrEmpty(entityId))
//                    {
//                        botEntity.MappingToBotEngine = string.Format("{0}", entityId);
//                    }
//                    else
//                    {
//                        throw new Exception(string.Format("Cannot find an application version with the version."));
//                    }

//                }
//            }
//            else
//            {
//                throw new Exception(string.Format("Cannot find an application version with the version."));
//            }

//        }
//        #endregion
//        #region 接口数据获取形式赋值
//        private void SetIntentIdForBotImportData(List<IntentModelAggregate> intentModelAggregateList, BotImportDataEx botImportData, Chatbot bot)
//        {
//            if (intentModelAggregateList != null && intentModelAggregateList.Count > 0)
//            {
//                foreach (BotCategoryTypeEx category in botImportData.Bot.Category)
//                {
//                    foreach (BotIntentTypeEx botIntent in category.Intent)
//                    {
//                        IntentModelAggregate intentModelAggregate = intentModelAggregateList.FirstOrDefault(a => a.IntentModel.IntentName == botIntent.IntentName);
//#if DEBUG
//                        intentModelAggregate = new IntentModelAggregate
//                        {
//                            IntentModel = new IntentModel
//                            {
//                                Id = Guid.NewGuid().ToString()
//                            }
//                        };
//#endif
//                        if (bot.EngineType == EnumBotType.comm100OwnBot)
//                        {//2019.6.20 comm100OwnBot
//                            intentModelAggregate = new IntentModelAggregate
//                            {
//                                IntentModel = new IntentModel
//                                {
//                                    Id = Guid.NewGuid().ToString()
//                                }
//                            };
//                        }

//                        if (intentModelAggregate != null)
//                        {
//                            string intentId = intentModelAggregate.IntentModel.Id;
//                            if (!string.IsNullOrEmpty(intentId))
//                            {
//                                botIntent.MappingToBotEngine = string.Format("{0}", intentId);
//                            }
//                        }
//                        else
//                        {
//                            throw new Exception(string.Format("Cannot find intent '{0}' an application version with the version.", botIntent.IntentName));
//                        }
//                    }
//                }
//            }
//            else
//            {
//                throw new Exception(string.Format("Cannot find any intent an application version with the version."));
//            }
//        }
//        private void SetEntityIdForBotImportData(List<EntityModelAggregate> entityModelAggregateList, BotImportDataEx botImportData, Chatbot bot)
//        {
//            if (entityModelAggregateList != null && entityModelAggregateList.Count > 0)
//            {
//                //过滤掉 系统Entity
//                BotEntityTypeEx[] botEntityTypeNoSystemEntity = botImportData.Bot.Entity.Where(a => a.EntityType == BotEntityTypeEntityType.List).ToArray();
//                foreach (BotEntityTypeEx botEntity in botEntityTypeNoSystemEntity)
//                {
//                    EntityModelAggregate entityModelAggregate = entityModelAggregateList.FirstOrDefault(a => a.EntityModel.EntityName == botEntity.EntityName);
//#if DEBUG
//                    entityModelAggregate = new EntityModelAggregate
//                    {
//                        EntityModel = new EntityModel
//                        {
//                            Id = Guid.NewGuid().ToString()
//                        }
//                    };
//#endif
//                    if (bot.EngineType == EnumBotType.comm100OwnBot)
//                    {//2019.6.20 comm100OwnBot
//                        entityModelAggregate = new EntityModelAggregate
//                        {
//                            EntityModel = new EntityModel
//                            {
//                                Id = Guid.NewGuid().ToString()
//                            }
//                        };
//                    }

//                    if (entityModelAggregate != null)
//                    {
//                        string entityId = entityModelAggregate.EntityModel.Id;
//                        botEntity.MappingToBotEngine = string.Format("{0}", entityId);
//                    }
//                    else
//                    {
//                        throw new Exception(string.Format("Cannot find entity an application version with the version.", botEntity.EntityName));
//                    }
//                }
//            }
//            else
//            {
//                throw new Exception(string.Format("Cannot find any entity an application version with the version."));
//            }
//        }
//        #endregion
//        private string GetKeyFromObjectMaps(dynamic obj, BotImportDataQueue botImportDataQueue)
//        {
//            string key = "";
//            key = botImportDataQueue.ObjectMaps.Keys.FirstOrDefault(a => a == obj.Guid);
//            return key;
//        }
//        private string BotImportData2Queue(BotImportDataQueue botImportDataQueue, BotImportDataEx botImportData)
//        {
//            string errorMessage = "";
//            try
//            {
//                //由于 Entity 可能存在多个，为了前端能够及时收到消息，一次只处理50条 EntityItem 数据
//                //Entity
//                //Entity EntityItem
//                if (botImportData.Bot.Entity != null)
//                {
//                    foreach (BotEntityTypeEx botEntity in botImportData.Bot.Entity)
//                    {
//                        string botEntityKey = Guid.NewGuid().ToString();
//                        botEntity.Guid = botEntityKey;
//                        botImportDataQueue.ObjectMaps.Add(botEntityKey, new { ObjectType = "BotEntityTypeEx", Object = botEntity });
//                        botImportDataQueue.ImportDataQueue.Enqueue(botEntityKey);

//                        if (botEntity.EntityItem != null)
//                        {
//                            foreach (BotListEntityItemTypeEx botListEntity in botEntity.EntityItem)
//                            {
//                                string botListEntityKey = Guid.NewGuid().ToString();
//                                botListEntity.Guid = botListEntityKey;
//                                botImportDataQueue.ObjectMaps.Add(botListEntityKey, new { ObjectType = "BotListEntityItemTypeEx", Object = botListEntity });

//                                string keyValue1 = string.Join("|", new string[] { botEntityKey, botListEntityKey });
//                                botImportDataQueue.ImportDataQueue.Enqueue(keyValue1);
//                            }
//                        }
//                    }
//                }

//                //t_Bot_BotCatagory
//                //t_Bot_BotIntents
//                //t_Bot_IntentQuestions
//                //t_Bot_IntentQuestionEntities
//                //t_Bot_IntentAnswerSignInSettings
//                //t_Bot_IntentAnswers
//                //t_Bot_IntentAnswerButtons
//                //t_Bot_EntityCollectionFormFields
//                //t_Bot_EntityCollectionPrompts
//                if (botImportData.Bot.Category != null)
//                {
//                    //因为有些对象需要Intent，所以Intent需要首先入库，这样定义一个List用于存储后续需要Intent ID 的数据后一步插入队列
//                    foreach (BotCategoryTypeEx category in botImportData.Bot.Category)
//                    {
//                        string categoryKey = Guid.NewGuid().ToString();
//                        category.Guid = categoryKey;
//                        botImportDataQueue.ObjectMaps.Add(categoryKey, new { ObjectType = "BotCategoryTypeEx", Object = category });

//                        botImportDataQueue.ImportDataQueue.Enqueue(categoryKey);

//                        if (category.Intent != null)
//                        {
//                            foreach (BotIntentTypeEx botIntent in category.Intent)
//                            {
//                                string botIntentKey = Guid.NewGuid().ToString();
//                                botIntent.Guid = botIntentKey;
//                                botImportDataQueue.ObjectMaps.Add(botIntentKey, new { ObjectType = "BotIntentTypeEx", Object = botIntent });

//                                string keyValue2 = string.Join("|", new string[] { categoryKey, botIntentKey });
//                                botImportDataQueue.ImportDataQueue.Enqueue(keyValue2);
//                            }
//                        }
//                    }

//                    foreach (BotCategoryTypeEx category in botImportData.Bot.Category)
//                    {
//                        string categoryKey = GetKeyFromObjectMaps(category, botImportDataQueue);

//                        if (category.Intent != null)
//                        {
//                            foreach (BotIntentTypeEx botIntent in category.Intent)
//                            {
//                                string botIntentKey = GetKeyFromObjectMaps(botIntent, botImportDataQueue);

//                                if (botIntent.Question != null)
//                                {
//                                    foreach (BotIntentQuestionTypeEx question in botIntent.Question)
//                                    {
//                                        string questionKey = Guid.NewGuid().ToString();
//                                        question.Guid = questionKey;
//                                        botImportDataQueue.ObjectMaps.Add(questionKey, new { ObjectType = "BotIntentQuestionTypeEx", Object = question });

//                                        string keyValue3 = string.Join("|", new string[] { botIntentKey, questionKey });
//                                        botImportDataQueue.ImportDataQueue.Enqueue(keyValue3);

//                                        if (question.QuestionEntity != null)
//                                        {
//                                            foreach (BotIntentQuestionEntityTypeEx questionEntity in question.QuestionEntity)
//                                            {
//                                                //通过EntityName查找到对应的botEntity
//                                                BotEntityTypeEx botEntity = botImportData.Bot.Entity.FirstOrDefault(a => a.EntityName == questionEntity.EntityName);
//                                                string botEntityKey = GetKeyFromObjectMaps(botEntity, botImportDataQueue);

//                                                string questionEntityKey = Guid.NewGuid().ToString();
//                                                questionEntity.Guid = questionEntityKey;
//                                                botImportDataQueue.ObjectMaps.Add(questionEntityKey, new { ObjectType = "BotIntentQuestionEntityTypeEx", Object = questionEntity });

//                                                string keyValue4 = string.Join("|", new string[] { botEntityKey, questionKey, questionEntityKey });
//                                                //KeyValuePair<KeyValuePair<BotEntityTypeEx, BotIntentQuestionTypeEx>, BotIntentQuestionEntityTypeEx> keyValue4 = new KeyValuePair<KeyValuePair<BotEntityTypeEx, BotIntentQuestionTypeEx>, BotIntentQuestionEntityTypeEx>(new KeyValuePair<BotEntityTypeEx, BotIntentQuestionTypeEx>(botEntity, question), questionEntity);
//                                                botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);
//                                            }
//                                        }
//                                    }
//                                }

//                                if (botIntent.IntentAnswers != null)
//                                {
//                                    foreach (BotIntentAnswerTypeEx botIntentAnswerTypeEx in botIntent.IntentAnswers)
//                                    {
//                                        string botIntentAnswerTypeExKey = Guid.NewGuid().ToString();
//                                        botIntentAnswerTypeEx.Guid = botIntentAnswerTypeExKey;
//                                        botImportDataQueue.ObjectMaps.Add(botIntentAnswerTypeExKey, new { ObjectType = "BotIntentAnswerTypeEx", Object = botIntentAnswerTypeEx });

//                                        string keyValue3 = string.Join("|", new string[] { botIntentKey, botIntentAnswerTypeExKey });
//                                        botImportDataQueue.ImportDataQueue.Enqueue(keyValue3);

//                                        if (botIntentAnswerTypeEx.IntentAnswerButtons != null)
//                                        {
//                                            foreach (BotIntentAnswerButtonTypeEx botIntentAnswerButtonTypeEx in botIntentAnswerTypeEx.IntentAnswerButtons)
//                                            {
//                                                string botIntentAnswerButtonTypeExKey = Guid.NewGuid().ToString();
//                                                botIntentAnswerButtonTypeEx.Guid = botIntentAnswerButtonTypeExKey;
//                                                botImportDataQueue.ObjectMaps.Add(botIntentAnswerButtonTypeExKey, new { ObjectType = "BotIntentAnswerButtonTypeEx", Object = botIntentAnswerButtonTypeEx });

//                                                if (botIntentAnswerButtonTypeEx.ButtonType == ButtonTypeType.goToIntent)
//                                                {
//                                                    //通过 IntentName 找到对应的 Intent
//                                                    string intentName = botIntentAnswerButtonTypeEx.UrlOrIntentName;
//                                                    //通过IntentName查找到对应的botIntent
//                                                    BotIntentTypeEx botIntentTypeEx = botImportData.Bot.Category.SelectMany(a => a.Intent).FirstOrDefault(a => a.IntentName == intentName);
//                                                    string botIntentTypeExKey = GetKeyFromObjectMaps(botIntentTypeEx, botImportDataQueue);
//                                                    string keyValue4 = string.Join("|", new string[] { botIntentKey, botIntentAnswerTypeExKey, botIntentTypeExKey, botIntentAnswerButtonTypeExKey });
//                                                    botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);

//                                                    //KeyValuePair<KeyValuePair<KeyValuePair<BotIntentTypeEx, BotIntentAnswerTypeEx>, BotIntentTypeEx>, BotIntentAnswerButtonTypeEx> keyValue4 =
//                                                    //    new KeyValuePair<KeyValuePair<KeyValuePair<BotIntentTypeEx, BotIntentAnswerTypeEx>, BotIntentTypeEx>, BotIntentAnswerButtonTypeEx>(
//                                                    //        new KeyValuePair<KeyValuePair<BotIntentTypeEx, BotIntentAnswerTypeEx>, BotIntentTypeEx>(
//                                                    //            new KeyValuePair<BotIntentTypeEx, BotIntentAnswerTypeEx>(botIntent, botIntentAnswerTypeEx), botIntentTypeEx), botIntentAnswerButtonTypeEx);

//                                                    //botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);
//                                                }
//                                                else
//                                                {
//                                                    string keyValue4 = string.Join("|", new string[] { botIntentKey, botIntentAnswerTypeExKey, botIntentAnswerButtonTypeExKey });

//                                                    //KeyValuePair<KeyValuePair<BotIntentTypeEx, BotIntentAnswerTypeEx>, BotIntentAnswerButtonTypeEx> keyValue4 = new KeyValuePair<KeyValuePair<BotIntentTypeEx, BotIntentAnswerTypeEx>, BotIntentAnswerButtonTypeEx>(new KeyValuePair<BotIntentTypeEx, BotIntentAnswerTypeEx>(botIntent, botIntentAnswerTypeEx), botIntentAnswerButtonTypeEx);
//                                                    botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);
//                                                }
//                                            }
//                                        }
//                                        if (botIntentAnswerTypeEx.AnswerSignInSettings != null)
//                                        {
//                                            foreach (BotAnswerSignInSettingTypeEx botAnswerSignInSettingTypeEx in botIntentAnswerTypeEx.AnswerSignInSettings)
//                                            {
//                                                string botAnswerSignInSettingTypeExKey = Guid.NewGuid().ToString();
//                                                botAnswerSignInSettingTypeEx.Guid = botAnswerSignInSettingTypeExKey;
//                                                botImportDataQueue.ObjectMaps.Add(botAnswerSignInSettingTypeExKey, new { ObjectType = "BotAnswerSignInSettingTypeEx", Object = botAnswerSignInSettingTypeEx });

//                                                string keyValue4 = string.Join("|", new string[] { botIntentKey, botIntentAnswerTypeExKey, botAnswerSignInSettingTypeExKey });
//                                                botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);
//                                            }
//                                        }
//                                        else
//                                        {
//                                            //支持历史intent级别的数据，解析的时候只解析到livechat渠道
//                                            if (botIntentAnswerTypeEx.ChannelType == "livechat")
//                                            {
//                                                if (botIntent.AnswerSignInSettings != null)
//                                                {
//                                                    foreach (BotAnswerSignInSettingTypeEx botAnswerSignInSettingTypeEx in botIntent.AnswerSignInSettings)
//                                                    {
//                                                        string botAnswerSignInSettingTypeExKey = Guid.NewGuid().ToString();
//                                                        botAnswerSignInSettingTypeEx.Guid = botAnswerSignInSettingTypeExKey;
//                                                        botImportDataQueue.ObjectMaps.Add(botAnswerSignInSettingTypeExKey, new { ObjectType = "BotAnswerSignInSettingTypeEx", Object = botAnswerSignInSettingTypeEx });

//                                                        string keyValue4 = string.Join("|", new string[] { botIntentKey, botIntentAnswerTypeExKey, botAnswerSignInSettingTypeExKey });
//                                                        botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);
//                                                    }
//                                                }
//                                            }
//                                        }
//                                        if (botIntentAnswerTypeEx.EntityCollectionFormFields != null)
//                                        {
//                                            foreach (BotEntityCollectionFormFieldTypeEx botEntityCollectionFormFieldTypeEx in botIntentAnswerTypeEx.EntityCollectionFormFields)
//                                            {
//                                                string botEntityCollectionFormFieldTypeExKey = Guid.NewGuid().ToString();
//                                                botEntityCollectionFormFieldTypeEx.Guid = botEntityCollectionFormFieldTypeExKey;
//                                                botImportDataQueue.ObjectMaps.Add(botEntityCollectionFormFieldTypeExKey, new { ObjectType = "BotEntityCollectionFormFieldTypeEx", Object = botEntityCollectionFormFieldTypeEx });

//                                                if (string.IsNullOrEmpty(botEntityCollectionFormFieldTypeEx.EntityName))
//                                                {     //2019.6.24 收集信息不必一定需要Entity
//                                                    string keyValue4 = string.Join("|", new string[] { botIntentKey, botIntentAnswerTypeExKey, botEntityCollectionFormFieldTypeExKey });

//                                                    //KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionFormFieldTypeEx> keyValue3 = new KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionFormFieldTypeEx>(new KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>(botIntent, botEntity), botEntityCollectionFormFieldTypeEx);
//                                                    botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);
//                                                }
//                                                else
//                                                {
//                                                    //通过EntityName查找到对应的botEntity
//                                                    BotEntityTypeEx botEntity = botImportData.Bot.Entity.FirstOrDefault(a => a.EntityName == botEntityCollectionFormFieldTypeEx.EntityName);
//                                                    string botEntityKey = GetKeyFromObjectMaps(botEntity, botImportDataQueue);
//                                                    string keyValue4 = string.Join("|", new string[] { botIntentKey, botEntityKey, botIntentAnswerTypeExKey, botEntityCollectionFormFieldTypeExKey });

//                                                    //KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionFormFieldTypeEx> keyValue3 = new KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionFormFieldTypeEx>(new KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>(botIntent, botEntity), botEntityCollectionFormFieldTypeEx);
//                                                    botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);
//                                                }

//                                            }
//                                        }
//                                        else
//                                        {
//                                            //支持历史intent级别的数据，解析的时候只解析到livechat渠道
//                                            if (botIntentAnswerTypeEx.ChannelType == "livechat")
//                                            {
//                                                if (botIntent.EntityCollectionFormFields != null)
//                                                {
//                                                    foreach (BotEntityCollectionFormFieldTypeEx botEntityCollectionFormFieldTypeEx in botIntent.EntityCollectionFormFields)
//                                                    {
//                                                        string botEntityCollectionFormFieldTypeExKey = Guid.NewGuid().ToString();
//                                                        botEntityCollectionFormFieldTypeEx.Guid = botEntityCollectionFormFieldTypeExKey;
//                                                        botImportDataQueue.ObjectMaps.Add(botEntityCollectionFormFieldTypeExKey, new { ObjectType = "BotEntityCollectionFormFieldTypeEx", Object = botEntityCollectionFormFieldTypeEx });

//                                                        if (string.IsNullOrEmpty(botEntityCollectionFormFieldTypeEx.EntityName))
//                                                        {     //2019.6.24 收集信息不必一定需要Entity
//                                                            string keyValue4 = string.Join("|", new string[] { botIntentKey, botIntentAnswerTypeExKey, botEntityCollectionFormFieldTypeExKey });

//                                                            //KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionFormFieldTypeEx> keyValue3 = new KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionFormFieldTypeEx>(new KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>(botIntent, botEntity), botEntityCollectionFormFieldTypeEx);
//                                                            botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);
//                                                        }
//                                                        else
//                                                        {
//                                                            //通过EntityName查找到对应的botEntity
//                                                            BotEntityTypeEx botEntity = botImportData.Bot.Entity.FirstOrDefault(a => a.EntityName == botEntityCollectionFormFieldTypeEx.EntityName);
//                                                            string botEntityKey = GetKeyFromObjectMaps(botEntity, botImportDataQueue);
//                                                            string keyValue4 = string.Join("|", new string[] { botIntentKey, botEntityKey, botIntentAnswerTypeExKey, botEntityCollectionFormFieldTypeExKey });

//                                                            //KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionFormFieldTypeEx> keyValue3 = new KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionFormFieldTypeEx>(new KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>(botIntent, botEntity), botEntityCollectionFormFieldTypeEx);
//                                                            botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);
//                                                        }

//                                                    }
//                                                }
//                                            }
//                                        }
//                                        if (botIntentAnswerTypeEx.EntityCollectionPrompts != null)
//                                        {
//                                            foreach (BotEntityCollectionPromptTypeEx botEntityCollectionPromptTypeEx in botIntentAnswerTypeEx.EntityCollectionPrompts)
//                                            {
//                                                string botEntityCollectionPromptTypeExKey = Guid.NewGuid().ToString();
//                                                botEntityCollectionPromptTypeEx.Guid = botEntityCollectionPromptTypeExKey;
//                                                botImportDataQueue.ObjectMaps.Add(botEntityCollectionPromptTypeExKey, new { ObjectType = "BotEntityCollectionPromptTypeEx", Object = botEntityCollectionPromptTypeEx });

//                                                //通过EntityName查找到对应的botEntity
//                                                BotEntityTypeEx botEntity = botImportData.Bot.Entity.FirstOrDefault(a => a.EntityName == botEntityCollectionPromptTypeEx.EntityName);
//                                                string botEntityKey = GetKeyFromObjectMaps(botEntity, botImportDataQueue);
//                                                string keyValue4 = string.Join("|", new string[] { botIntentKey, botEntityKey, botIntentAnswerTypeExKey, botEntityCollectionPromptTypeExKey });

//                                                //KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionPromptTypeEx> keyValue3 = new KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionPromptTypeEx>(new KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>(botIntent, botEntity), botEntityCollectionPromptTypeEx);
//                                                botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);
//                                            }
//                                        }
//                                        else
//                                        {
//                                            //支持历史intent级别的数据，解析的时候只解析到livechat渠道
//                                            if (botIntentAnswerTypeEx.ChannelType == "livechat")
//                                            {
//                                                if (botIntent.EntityCollectionPrompts != null)
//                                                {
//                                                    foreach (BotEntityCollectionPromptTypeEx botEntityCollectionPromptTypeEx in botIntent.EntityCollectionPrompts)
//                                                    {
//                                                        string botEntityCollectionPromptTypeExKey = Guid.NewGuid().ToString();
//                                                        botEntityCollectionPromptTypeEx.Guid = botEntityCollectionPromptTypeExKey;
//                                                        botImportDataQueue.ObjectMaps.Add(botEntityCollectionPromptTypeExKey, new { ObjectType = "BotEntityCollectionPromptTypeEx", Object = botEntityCollectionPromptTypeEx });

//                                                        //通过EntityName查找到对应的botEntity
//                                                        BotEntityTypeEx botEntity = botImportData.Bot.Entity.FirstOrDefault(a => a.EntityName == botEntityCollectionPromptTypeEx.EntityName);
//                                                        string botEntityKey = GetKeyFromObjectMaps(botEntity, botImportDataQueue);
//                                                        string keyValue4 = string.Join("|", new string[] { botIntentKey, botEntityKey, botIntentAnswerTypeExKey, botEntityCollectionPromptTypeExKey });

//                                                        //KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionPromptTypeEx> keyValue3 = new KeyValuePair<KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>, BotEntityCollectionPromptTypeEx>(new KeyValuePair<BotIntentTypeEx, BotEntityTypeEx>(botIntent, botEntity), botEntityCollectionPromptTypeEx);
//                                                        botImportDataQueue.ImportDataQueue.Enqueue(keyValue4);
//                                                    }
//                                                }
//                                            }
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }

//                //t_Bot_QuickReply
//                //t_Bot_QuickReplyItems
//                if (botImportData.Bot.QuickReplys != null)
//                {
//                    foreach (BotQuickReplyTypeEx botQuickReplyTypeEx in botImportData.Bot.QuickReplys)
//                    {
//                        string botQuickReplyTypeExKey = Guid.NewGuid().ToString();
//                        botQuickReplyTypeEx.Guid = botQuickReplyTypeExKey;
//                        botImportDataQueue.ObjectMaps.Add(botQuickReplyTypeExKey, new { ObjectType = "BotQuickReplyTypeEx", Object = botQuickReplyTypeEx });

//                        botImportDataQueue.ImportDataQueue.Enqueue(botQuickReplyTypeExKey);

//                        if (botQuickReplyTypeEx.QuickReplyItems != null)
//                        {
//                            foreach (BotQuickReplyItemTypeEx botQuickReplyItemTypeEx in botQuickReplyTypeEx.QuickReplyItems)
//                            {
//                                string botQuickReplyItemTypeExKey = Guid.NewGuid().ToString();
//                                botQuickReplyItemTypeEx.Guid = botQuickReplyItemTypeExKey;
//                                botImportDataQueue.ObjectMaps.Add(botQuickReplyItemTypeExKey, new { ObjectType = "BotQuickReplyItemTypeEx", Object = botQuickReplyItemTypeEx });

//                                if (botQuickReplyItemTypeEx.Type == BotQuickReplyItemTypeType.goToIntent)
//                                {
//                                    //通过IntentName查找到对应的botIntent
//                                    BotIntentTypeEx botIntent = botImportData.Bot.Category.SelectMany(a => a.Intent).FirstOrDefault(a => a.IntentName == botQuickReplyItemTypeEx.IntentName);
//                                    string botIntentKey = GetKeyFromObjectMaps(botIntent, botImportDataQueue);
//                                    string keyValue1 = string.Join("|", new string[] { botQuickReplyTypeExKey, botIntentKey, botQuickReplyItemTypeExKey });

//                                    //KeyValuePair<KeyValuePair<BotQuickReplyTypeEx, BotIntentTypeEx>, BotQuickReplyItemTypeEx> keyValue1 = new KeyValuePair<KeyValuePair<BotQuickReplyTypeEx, BotIntentTypeEx>, BotQuickReplyItemTypeEx>(new KeyValuePair<BotQuickReplyTypeEx, BotIntentTypeEx>(botQuickReplyTypeEx, botIntent), botQuickReplyItemTypeEx);
//                                    botImportDataQueue.ImportDataQueue.Enqueue(keyValue1);
//                                }
//                                else
//                                {
//                                    string keyValue1 = string.Join("|", new string[] { botQuickReplyTypeExKey, botQuickReplyItemTypeExKey });

//                                    //KeyValuePair<BotQuickReplyTypeEx, BotQuickReplyItemTypeEx> keyValue1 = new KeyValuePair<BotQuickReplyTypeEx, BotQuickReplyItemTypeEx>(botQuickReplyTypeEx, botQuickReplyItemTypeEx);
//                                    botImportDataQueue.ImportDataQueue.Enqueue(keyValue1);
//                                }
//                            }
//                        }
//                    }
//                }

//                //t_Bot_SmartTriggers
//                //t_Bot_SmartTriggerConditions
//                //t_Bot_SmartTriggerActions
//                if (botImportData.Bot.SmartTriggers != null)
//                {
//                    foreach (BotSmartTriggerTypeEx botSmartTriggerTypeEx in botImportData.Bot.SmartTriggers)
//                    {
//                        string botSmartTriggerTypeExKey = Guid.NewGuid().ToString();
//                        botSmartTriggerTypeEx.Guid = botSmartTriggerTypeExKey;
//                        botImportDataQueue.ObjectMaps.Add(botSmartTriggerTypeExKey, new { ObjectType = "BotSmartTriggerTypeEx", Object = botSmartTriggerTypeEx });

//                        botImportDataQueue.ImportDataQueue.Enqueue(botSmartTriggerTypeExKey);

//                        if (botSmartTriggerTypeEx.SmartTriggerConditions != null)
//                        {
//                            foreach (BotSmartTriggerConditionTypeEx botSmartTriggerConditionTypeEx in botSmartTriggerTypeEx.SmartTriggerConditions)
//                            {
//                                string botSmartTriggerConditionTypeExKey = Guid.NewGuid().ToString();
//                                botSmartTriggerConditionTypeEx.Guid = botSmartTriggerConditionTypeExKey;
//                                botImportDataQueue.ObjectMaps.Add(botSmartTriggerConditionTypeExKey, new { ObjectType = "BotSmartTriggerConditionTypeEx", Object = botSmartTriggerConditionTypeEx });
//                                string keyValue1 = string.Join("|", new string[] { botSmartTriggerTypeExKey, botSmartTriggerConditionTypeExKey });

//                                //KeyValuePair<BotSmartTriggerTypeEx, BotSmartTriggerConditionTypeEx> keyValue1 = new KeyValuePair<BotSmartTriggerTypeEx, BotSmartTriggerConditionTypeEx>(botSmartTriggerTypeEx, botSmartTriggerConditionTypeEx);
//                                botImportDataQueue.ImportDataQueue.Enqueue(keyValue1);
//                            }
//                        }
//                        if (botSmartTriggerTypeEx.SmartTriggerActions != null)
//                        {
//                            foreach (BotSmartTriggerActionTypeEx botSmartTriggerActionTypeEx in botSmartTriggerTypeEx.SmartTriggerActions)
//                            {
//                                string botSmartTriggerActionTypeExKey = Guid.NewGuid().ToString();
//                                botSmartTriggerActionTypeEx.Guid = botSmartTriggerActionTypeExKey;
//                                botImportDataQueue.ObjectMaps.Add(botSmartTriggerActionTypeExKey, new { ObjectType = "BotSmartTriggerActionTypeEx", Object = botSmartTriggerActionTypeEx });
//                                string keyValue1 = string.Join("|", new string[] { botSmartTriggerTypeExKey, botSmartTriggerActionTypeExKey });

//                                //KeyValuePair<BotSmartTriggerTypeEx, BotSmartTriggerActionTypeEx> keyValue1 = new KeyValuePair<BotSmartTriggerTypeEx, BotSmartTriggerActionTypeEx>(botSmartTriggerTypeEx, botSmartTriggerActionTypeEx);
//                                botImportDataQueue.ImportDataQueue.Enqueue(keyValue1);
//                            }
//                        }
//                    }
//                }

//                //greetingMessage
//                //t_Bot_IntentAnswers
//                //t_Bot_IntentAnswerButtons
//                if (botImportData.Bot.GreetingMessage != null)
//                {
//                    foreach (AnswerTypeEx answerTypeEx in botImportData.Bot.GreetingMessage)
//                    {
//                        string answerTypeExKey = Guid.NewGuid().ToString();
//                        answerTypeEx.Guid = answerTypeExKey;
//                        botImportDataQueue.ObjectMaps.Add(answerTypeExKey, new { ObjectType = "AnswerTypeEx", Object = answerTypeEx });

//                        if (answerTypeEx.Type == AnswerTypeType.quickReply)
//                        {
//                            string quickReplyName = answerTypeEx.Content.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.RemoveEmptyEntries)?[1];
//                            BotQuickReplyTypeEx botQuickReplyTypeEx = botImportData.Bot.QuickReplys.FirstOrDefault(a => a.Name == quickReplyName);
//                            string botQuickReplyTypeExKey = GetKeyFromObjectMaps(botQuickReplyTypeEx, botImportDataQueue);

//                            //KeyValuePair<BotQuickReplyTypeEx, AnswerTypeEx > keyValue =
//                            //new KeyValuePair<BotQuickReplyTypeEx, AnswerTypeEx>(botQuickReplyTypeEx, answerTypeEx);
//                            string keyValue = string.Join("|", new string[] { botQuickReplyTypeExKey, answerTypeExKey });

//                            botImportDataQueue.ImportDataQueue.Enqueue(keyValue);
//                        }
//                        else
//                        {
//                            botImportDataQueue.ImportDataQueue.Enqueue(answerTypeExKey);
//                        }


//                        if (answerTypeEx.Buttons != null)
//                        {
//                            foreach (ButtonTypeEx buttonTypeEx in answerTypeEx.Buttons)
//                            {
//                                string buttonTypeExKey = Guid.NewGuid().ToString();
//                                buttonTypeEx.Guid = buttonTypeExKey;
//                                botImportDataQueue.ObjectMaps.Add(buttonTypeExKey, new { ObjectType = "ButtonTypeEx", Object = buttonTypeEx });

//                                if (buttonTypeEx.Type == ButtonTypeType.goToIntent)
//                                {
//                                    //通过 IntentName 找到对应的 Intent
//                                    string intentName = buttonTypeEx.UrlOrIntentName;
//                                    //通过IntentName查找到对应的botIntent
//                                    BotIntentTypeEx botIntentTypeEx = botImportData.Bot.Category.SelectMany(a => a.Intent).FirstOrDefault(a => a.IntentName == intentName);
//                                    string botIntentTypeExKey = GetKeyFromObjectMaps(botIntentTypeEx, botImportDataQueue);

//                                    //KeyValuePair<KeyValuePair<AnswerTypeEx, BotIntentTypeEx>, ButtonTypeEx> keyValue =
//                                    //    new KeyValuePair<KeyValuePair<AnswerTypeEx, BotIntentTypeEx>, ButtonTypeEx>(
//                                    //        new KeyValuePair<AnswerTypeEx, BotIntentTypeEx>(answerTypeEx, botIntentTypeEx), buttonTypeEx);
//                                    string keyValue = string.Join("|", new string[] { answerTypeExKey, botIntentTypeExKey, buttonTypeExKey });

//                                    botImportDataQueue.ImportDataQueue.Enqueue(keyValue);
//                                }
//                                else
//                                {
//                                    string keyValue2 = string.Join("|", new string[] { answerTypeExKey, buttonTypeExKey });

//                                    //KeyValuePair<AnswerTypeEx, ButtonTypeEx> keyValue2 = new KeyValuePair<AnswerTypeEx, ButtonTypeEx>(answerTypeEx, buttonTypeEx);
//                                    botImportDataQueue.ImportDataQueue.Enqueue(keyValue2);
//                                }
//                            }
//                        }
//                    }
//                }

//                //noAnswerMessage
//                if (botImportData.Bot.NoAnswerMessages != null)
//                {
//                    foreach (UnrecognizedMessageTypeEx unrecognizedMessageTypeEx in botImportData.Bot.NoAnswerMessages)
//                    {
//                        string unrecognizedMessageTypeExKey = Guid.NewGuid().ToString();
//                        unrecognizedMessageTypeEx.Guid = unrecognizedMessageTypeExKey;
//                        botImportDataQueue.ObjectMaps.Add(unrecognizedMessageTypeExKey, new { ObjectType = "UnrecognizedMessageTypeEx", Object = unrecognizedMessageTypeEx });
//                        string keyValue = string.Join("|", new string[] { "NoAnswerMessage", unrecognizedMessageTypeExKey });

//                        botImportDataQueue.ImportDataQueue.Enqueue(keyValue);
//                    }
//                }
//                else
//                {
//                    //支持历史数据导入，从Bot数据取数据组装数据存入default渠道
//                    botImportData.Bot.NoAnswerMessages = new UnrecognizedMessageTypeEx[] {
//                        new UnrecognizedMessageTypeEx{
//                            Channel = "default",
//                            Message = botImportData.Bot.NoResponseMessage,
//                            IncludeContactAnAgentOption= true,
//                            IsEnabled=true,
//                        }
//                    };
//                    foreach (UnrecognizedMessageTypeEx unrecognizedMessageTypeEx in botImportData.Bot.NoAnswerMessages)
//                    {
//                        string unrecognizedMessageTypeExKey = Guid.NewGuid().ToString();
//                        unrecognizedMessageTypeEx.Guid = unrecognizedMessageTypeExKey;
//                        botImportDataQueue.ObjectMaps.Add(unrecognizedMessageTypeExKey, new { ObjectType = "UnrecognizedMessageTypeEx", Object = unrecognizedMessageTypeEx });
//                        string keyValue = string.Join("|", new string[] { "NoAnswerMessage", unrecognizedMessageTypeExKey });

//                        botImportDataQueue.ImportDataQueue.Enqueue(keyValue);
//                    }
//                }

//                //possibleAnswerMessage
//                if (botImportData.Bot.PossibleAnswerMessages != null)
//                {
//                    foreach (UnrecognizedMessageTypeEx unrecognizedMessageTypeEx in botImportData.Bot.PossibleAnswerMessages)
//                    {
//                        string unrecognizedMessageTypeExKey = Guid.NewGuid().ToString();
//                        unrecognizedMessageTypeEx.Guid = unrecognizedMessageTypeExKey;
//                        botImportDataQueue.ObjectMaps.Add(unrecognizedMessageTypeExKey, new { ObjectType = "UnrecognizedMessageTypeEx", Object = unrecognizedMessageTypeEx });
//                        string keyValue = string.Join("|", new string[] { "PossibleAnswerMessage", unrecognizedMessageTypeExKey });

//                        botImportDataQueue.ImportDataQueue.Enqueue(keyValue);
//                    }
//                }
//                else
//                {
//                    //支持历史数据导入，从Bot数据取数据组装数据存入default渠道
//                    botImportData.Bot.PossibleAnswerMessages = new UnrecognizedMessageTypeEx[] {
//                        new UnrecognizedMessageTypeEx{
//                            Channel = "default",
//                            Message = botImportData.Bot.PossibleResponsesExceedThresholdMessage,
//                            IncludeContactAnAgentOption = true,
//                            IsEnabled=true,
//                        }
//                    };
//                    foreach (UnrecognizedMessageTypeEx unrecognizedMessageTypeEx in botImportData.Bot.PossibleAnswerMessages)
//                    {
//                        string unrecognizedMessageTypeExKey = Guid.NewGuid().ToString();
//                        unrecognizedMessageTypeEx.Guid = unrecognizedMessageTypeExKey;
//                        botImportDataQueue.ObjectMaps.Add(unrecognizedMessageTypeExKey, new { ObjectType = "UnrecognizedMessageTypeEx", Object = unrecognizedMessageTypeEx });
//                        string keyValue = string.Join("|", new string[] { "PossibleAnswerMessage", unrecognizedMessageTypeExKey });

//                        botImportDataQueue.ImportDataQueue.Enqueue(keyValue);
//                    }
//                }

//                if (botImportData.Bot != null)
//                {
//                    string botKey = Guid.NewGuid().ToString();
//                    botImportData.Bot.Guid = botKey;
//                    botImportDataQueue.ObjectMaps.Add(botKey, new { ObjectType = "BotTypeEx", Object = botImportData.Bot });

//                    //Bot
//                    botImportDataQueue.ImportDataQueue.Enqueue(botKey);
//                }
//            }
//            catch (Exception e)
//            {
//                errorMessage = e.Message;
//            }
//            finally
//            {

//            }
//            return errorMessage;
//        }

//        private dynamic GetQueueObject(dynamic data)
//        {
//            dynamic obj = null;
//            switch (Convert.ToString(data.ObjectType))
//            {
//                case "BotEntityTypeEx":
//                    {
//                        if (data.Object is BotEntityTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotEntityTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotListEntityItemTypeEx":
//                    {
//                        if (data.Object is BotListEntityItemTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotListEntityItemTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotCategoryTypeEx":
//                    {
//                        if (data.Object is BotCategoryTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotCategoryTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotIntentTypeEx":
//                    {
//                        if (data.Object is BotIntentTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotIntentTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotIntentQuestionTypeEx":
//                    {
//                        if (data.Object is BotIntentQuestionTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotIntentQuestionTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotIntentQuestionEntityTypeEx":
//                    {
//                        if (data.Object is BotIntentQuestionEntityTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotIntentQuestionEntityTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotAnswerSignInSettingTypeEx":
//                    {
//                        if (data.Object is BotAnswerSignInSettingTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotAnswerSignInSettingTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotIntentAnswerTypeEx":
//                    {
//                        if (data.Object is BotIntentAnswerTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotIntentAnswerTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotIntentAnswerButtonTypeEx":
//                    {
//                        if (data.Object is BotIntentAnswerButtonTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotIntentAnswerButtonTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotEntityCollectionFormFieldTypeEx":
//                    {
//                        if (data.Object is BotEntityCollectionFormFieldTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotEntityCollectionFormFieldTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotEntityCollectionPromptTypeEx":
//                    {
//                        if (data.Object is BotEntityCollectionPromptTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotEntityCollectionPromptTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotQuickReplyTypeEx":
//                    {
//                        if (data.Object is BotQuickReplyTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotQuickReplyTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotQuickReplyItemTypeEx":
//                    {
//                        if (data.Object is BotQuickReplyItemTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotQuickReplyItemTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotSmartTriggerTypeEx":
//                    {
//                        if (data.Object is BotSmartTriggerTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotSmartTriggerTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotSmartTriggerConditionTypeEx":
//                    {
//                        if (data.Object is BotSmartTriggerConditionTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotSmartTriggerConditionTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotSmartTriggerActionTypeEx":
//                    {
//                        if (data.Object is BotSmartTriggerActionTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotSmartTriggerActionTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "AnswerTypeEx":
//                    {
//                        if (data.Object is AnswerTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<AnswerTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "ButtonTypeEx":
//                    {
//                        if (data.Object is ButtonTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<ButtonTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "BotTypeEx":
//                    {
//                        if (data.Object is BotTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<BotTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//                case "UnrecognizedMessageTypeEx":
//                    {
//                        if (data.Object is UnrecognizedMessageTypeEx)
//                        {
//                            obj = data.Object;
//                        }
//                        else
//                        {
//                            obj = JsonConvert.DeserializeObject<UnrecognizedMessageTypeEx>(Convert.ToString(data.Object));
//                        }
//                        break;
//                    }
//            }
//            return obj;
//        }
//        private string SaveDbForBotImportData(BotImportDataQueue botImportDataQueue, Chatbot bot)
//        {
//            string errorMessage = "";
//            try
//            {
//                IIntentDomainService intentDomainService = _container.Resolve<IIntentDomainService>();
//                IQuickReplyDomainService quickReplyDomainService = _container.Resolve<IQuickReplyDomainService>();
//                IGreetingMessageInChannelDomainService greetingMessageInChannelDomainService = _container.Resolve<IGreetingMessageInChannelDomainService>();
//                IResponseDomainService responseDomainService = _container.Resolve<IResponseDomainService>();
//                IEntityDomainService entityDomainService = _container.Resolve<IEntityDomainService>();
//                IEntityKeywordDomainService entityKeywordDomainService = _container.Resolve<IEntityKeywordDomainService>();
//                ICategoryDomainService categoryDomainService = _container.Resolve<ICategoryDomainService>();
//                IIntentQuestionDomainService intentQuestionDomainService = _container.Resolve<IIntentQuestionDomainService>();
//                IIntentQuestionSelectedKeywordDomainService intentQuestionSelectedKeywordDomainService = _container.Resolve<IIntentQuestionSelectedKeywordDomainService>();
//                IAnswerInChannelAuthenticationRequestDomainService answerInChannelAuthenticationRequestDomainService = _container.Resolve<IAnswerInChannelAuthenticationRequestDomainService>();
//                IIntentAnswerInChannelDomainService intentAnswerInChannelDomainService = _container.Resolve<IIntentAnswerInChannelDomainService>();
//                IResponseButtonDomainService responseButtonDomainService = _container.Resolve<IResponseButtonDomainService>();
//                IAnswerInChannelFormDomainService answerInChannelFormDomainService = _container.Resolve<IAnswerInChannelFormDomainService>();
//                IAnswerInChannelFormFieldDomainService answerInChannelFormFieldDomainService = _container.Resolve<IAnswerInChannelFormFieldDomainService>();
//                IAnswerInChannelPromptDomainService answerInChannelPromptDomainService = _container.Resolve<IAnswerInChannelPromptDomainService>();
//                IQuickReplyItemDomainService quickReplyItemDomainService = _container.Resolve<IQuickReplyItemDomainService>();
//                ISmartTriggerDomainService smartTriggerDomainService = _container.Resolve<ISmartTriggerDomainService>();
//                ISmartTriggerConditionDomainService smartTriggerConditionDomainService = _container.Resolve<ISmartTriggerConditionDomainService>();
//                ISmartTriggerActionDomainService smartTriggerActionDomainService = _container.Resolve<ISmartTriggerActionDomainService>();
//                INoAnswerMessageInChannelDomainService noAnswerMessageInChannelDomainService = _container.Resolve<INoAnswerMessageInChannelDomainService>();
//                IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService = _container.Resolve<IMessageAfterSeveralConsecutivePossibleAnswersInChannelDomainService>();

//                //为了前端能够及时收到消息，一次只处理50条
//                int index = 0;
//                IntentAnswerInChannel intentAnswerInChannel = null;
//                GreetingMessageInChannel greetingMessageInChannel = null;                

//                while (botImportDataQueue.ImportDataQueue.Count > 0)
//                {
//                    if (index > 50)
//                    {
//                        break;
//                    }
//                    else
//                    {
//                        string key = Convert.ToString(botImportDataQueue.ImportDataQueue.Dequeue());
//                        string lastKey = key.Split('|').LastOrDefault();
//                        dynamic data = GetQueueObject(botImportDataQueue.ObjectMaps[lastKey]);
//                        Type type = data.GetType();

//                        if (type == typeof(BotTypeEx))
//                        {
//                            //更新 t_Bot_Bots 数据
//                            var bots = Mapper.Map<ChatbotUpdateBo>(botImportDataQueue.BotImportData.Bot);                            
//                            bots.AvatarId = Guid.Parse("");//默认的图片ID
//                            Update(bot.Id, bots);
//                        }
//                        else if (type == typeof(BotEntityTypeEx))
//                        {
//                            //更新 t_Bot_BotEntities 数据
//                            data.SiteId = botImportDataQueue.SiteId;
//                            data.BotId = botImportDataQueue.BotId;
//                            BotEntityTypeEx botEntityTypeEx = data as BotEntityTypeEx;
//                            var botEntities = Mapper.Map<Entity>(botEntityTypeEx);
//                            if (botEntityTypeEx.EntityType == BotEntityTypeEntityType.Prebuilt)
//                            {
//                                botEntities.MappingToDialogflowId = "Do_not_need_to_synchronized_to_Dialogflow";
//                            }
//                            else
//                            {
//                                //list类型entity，displayname以entityname为准
//                                //botEntities.DisplayName = botEntities.EntityName;
//                            }
//                            botEntities = entityDomainService.Create(botEntities);
//                            if (botEntities != null && botEntities.Id != Guid.Empty)
//                            {
//                                data.Id = botEntities.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotEntityTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save bot entity fail");
//                            }
//                        }
//                        else if (type == typeof(BotListEntityItemTypeEx))
//                        {
//                            //保存 t_Bot_ListEntityItems
//                            string paramKey1 = key.Split('|')[0];
//                            BotEntityTypeEx botEntity = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotEntityTypeEx;
//                            BotListEntityItemTypeEx botListEntityItem = data as BotListEntityItemTypeEx;

//                            botListEntityItem.EntityId = botEntity.Id;
//                            botListEntityItem.SiteId = botImportDataQueue.SiteId;
//                            botListEntityItem.MappingToBotEngine = botEntity.MappingToBotEngine;//数据库中非空

//                            var listEntityItem = Mapper.Map<EntityKeyword>(botListEntityItem);
//                            entityKeywordDomainService.Create(listEntityItem);

//                        }
//                        else if (type == typeof(BotCategoryTypeEx))
//                        {
//                            //保存 t_Bot_BotCatagory
//                            BotCategoryTypeEx category = data as BotCategoryTypeEx;
//                            Guid categoryId = categoryDomainService.CreateCategory(botImportDataQueue.BotId, category.CatagoryName);
//                            if (categoryId != Guid.Empty)
//                            {
//                                data.Id = categoryId;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotCategoryTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save bot category fail");
//                            }
//                            //LogHelper.Debug(JsonConvert.SerializeObject(new
//                            //{
//                            //    BotCategoryTypeEx = data
//                            //}));
//                        }
//                        else if (type == typeof(BotIntentTypeEx))
//                        {
//                            //保存 t_Bot_BotIntents
//                            string paramKey1 = key.Split('|')[0];
//                            BotCategoryTypeEx botCategory = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotCategoryTypeEx;

//                            BotIntentTypeEx botIntent = data as BotIntentTypeEx;
//                            botIntent.CategoryId = botCategory.Id;
//                            botIntent.SiteId = botImportDataQueue.SiteId;
//                            botIntent.BotId = botImportDataQueue.BotId;

//                            var botIntents = Mapper.Map<Intent>(botIntent);
//                            botIntents = intentDomainService.Create(botIntents);
//                            if (botIntents != null && botIntents.Id != Guid.Empty)
//                            {
//                                botIntent.Id = botIntents.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotIntentTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save bot intent fail");
//                            }
//                            //LogHelper.Debug(JsonConvert.SerializeObject(new
//                            //{
//                            //    BotCategoryTypeEx = botCategory,
//                            //    BotIntentTypeEx = botIntent
//                            //}));
//                        }
//                        else if (type == typeof(BotIntentQuestionTypeEx))
//                        {
//                            //保存 t_Bot_IntentQuestions
//                            string paramKey1 = key.Split('|')[0];
//                            BotIntentTypeEx botIntent = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotIntentTypeEx;
//                            BotIntentQuestionTypeEx botIntentQuestion = data as BotIntentQuestionTypeEx;

//                            botIntentQuestion.IntentId = botIntent.Id;
//                            botIntentQuestion.SiteId = botImportDataQueue.SiteId;
//                            botIntentQuestion.IdInBotEngine = botIntent.MappingToBotEngine;//数据库中非空

//                            var intentQuestions = Mapper.Map<IntentQuestion>(botIntentQuestion);
//                            intentQuestions = intentQuestionDomainService.Create(intentQuestions);
//                            if (intentQuestions != null && intentQuestions.Id != Guid.Empty)
//                            {
//                                botIntentQuestion.Id = intentQuestions.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotIntentQuestionTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save bot intent question fail");
//                            }
//                            //LogHelper.Debug(JsonConvert.SerializeObject(new
//                            //{
//                            //    BotIntentTypeEx = botIntent,
//                            //    BotIntentQuestionTypeEx = botIntentQuestion
//                            //}));
//                        }
//                        else if (type == typeof(BotIntentQuestionEntityTypeEx))
//                        {
//                            //保存 t_Bot_IntentQuestionEntities
//                            string paramKey1 = key.Split('|')[0];
//                            string paramKey2 = key.Split('|')[1];
//                            BotEntityTypeEx botEntity = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotEntityTypeEx;
//                            BotIntentQuestionTypeEx botIntentQuestion = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey2]) as BotIntentQuestionTypeEx;

//                            BotIntentQuestionEntityTypeEx botIntentQuestionEntity = data as BotIntentQuestionEntityTypeEx;
//                            botIntentQuestionEntity.QuestionId = botIntentQuestion.Id;
//                            botIntentQuestionEntity.EntityId = botEntity.Id;
//                            botIntentQuestionEntity.SiteId = botImportDataQueue.SiteId;

//                            var intentQuestionEntities = Mapper.Map<IntentQuestionSelectedKeyword>(botIntentQuestionEntity);

//                            intentQuestionEntities = intentQuestionSelectedKeywordDomainService.Create(intentQuestionEntities);
//                            if (intentQuestionEntities != null && intentQuestionEntities.Id != Guid.Empty)
//                            {
//                                botIntentQuestionEntity.Id = intentQuestionEntities.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotIntentQuestionEntityTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save bot intent question entity fail");
//                            }

//                            //LogHelper.Debug(JsonConvert.SerializeObject(new
//                            //{
//                            //    BotEntityTypeEx = botEntity,
//                            //    BotIntentQuestionTypeEx = botIntentQuestion,
//                            //    BotIntentQuestionEntityTypeEx = botIntentQuestionEntity
//                            //}));
//                        }
//                        else if (type == typeof(BotAnswerSignInSettingTypeEx))
//                        {
//                            //保存 t_Bot_IntentAnswerSignInSettings
//                            string paramKey1 = key.Split('|')[0];
//                            string paramKey2 = key.Split('|')[1];
//                            BotIntentTypeEx botIntent = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotIntentTypeEx;
//                            BotIntentAnswerTypeEx botIntentAnswer = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey2]) as BotIntentAnswerTypeEx;
//                            BotAnswerSignInSettingTypeEx botAnswerSignInSetting = data as BotAnswerSignInSettingTypeEx;
//                            botAnswerSignInSetting.SiteId = botImportDataQueue.SiteId;
//                            botAnswerSignInSetting.IntentId = botIntent.Id;
//                            botAnswerSignInSetting.SignInURL = string.IsNullOrEmpty(botAnswerSignInSetting.SignInURL) ? "" : botAnswerSignInSetting.SignInURL;
//                            botAnswerSignInSetting.AnswerId = botIntentAnswer.Id;

//                            var answerSignInSettings = Mapper.Map<AnswerInChannelAuthenticationRequest>(botAnswerSignInSetting);
//                            answerSignInSettings = answerInChannelAuthenticationRequestDomainService.Create(answerSignInSettings);
//                            if (answerSignInSettings != null && answerSignInSettings.Id != Guid.Empty)
//                            {
//                                botAnswerSignInSetting.Id = answerSignInSettings.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotAnswerSignInSettingTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save intent answer sign setting fail");
//                            }

//                            if(intentAnswerInChannel == null)
//                            {
//                                intentAnswerInChannel = intentAnswerInChannelDomainService.GetByIntentIdAndChannel(botAnswerSignInSetting.IntentId, botAnswerSignInSetting.ChannelType);
//                                if (intentAnswerInChannel == null
//                                    || intentAnswerInChannel.Id == Guid.Empty)
//                                {
//                                    intentAnswerInChannel = new IntentAnswerInChannel
//                                    {
//                                        Id = Guid.NewGuid(),
//                                        IntentId = botAnswerSignInSetting.IntentId,
//                                        Channel = botAnswerSignInSetting.ChannelType,
//                                        AuthenticationRequestId = answerSignInSettings.Id,
//                                    };
//                                    intentAnswerInChannelDomainService.Create(intentAnswerInChannel);
//                                }
//                            }
//                            else
//                            {
//                                intentAnswerInChannel.AuthenticationRequestId = answerSignInSettings.Id;
//                                var intentAnswerInChannelUpdateBo = Mapper.Map<IntentAnswerInChannelUpdateBo>(intentAnswerInChannel);
//                                intentAnswerInChannelDomainService.Update(intentAnswerInChannelUpdateBo);
//                            }
//                        }
//                        else if (type == typeof(BotIntentAnswerTypeEx))
//                        {
//                            //保存 t_Bot_IntentAnswers
//                            string paramKey1 = key.Split('|')[0];
//                            BotIntentTypeEx botIntent = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotIntentTypeEx;
//                            BotIntentAnswerTypeEx botIntentAnswer = data as BotIntentAnswerTypeEx;
//                            botIntentAnswer.SiteId = botImportDataQueue.SiteId;
//                            botIntentAnswer.BotId = botImportDataQueue.BotId;
//                            botIntentAnswer.IntentId = botIntent.Id;

//                            if(intentAnswerInChannel == null)
//                            {
//                                intentAnswerInChannel = intentAnswerInChannelDomainService.GetByIntentIdAndChannel(botIntentAnswer.IntentId, botIntentAnswer.ChannelType);
//                                if (intentAnswerInChannel == null
//                                    || intentAnswerInChannel.Id == Guid.Empty)
//                                {
//                                    intentAnswerInChannel = new IntentAnswerInChannel
//                                    {
//                                        Id = Guid.NewGuid(),
//                                        IntentId = botIntentAnswer.IntentId,
//                                        Channel = botIntentAnswer.ChannelType,
//                                    };
//                                    intentAnswerInChannelDomainService.Create(intentAnswerInChannel);
//                                }
//                            }
//                            Response response = null;

//                            if (botIntentAnswer.AnswerType == AnswerTypeType.text)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = intentAnswerInChannel.Id,
//                                    Type = EnumAnswerType.text,
//                                    TextVariants = JsonConvert.SerializeObject(botIntentAnswer.Answer.Split(Utils.GeneralSeparator)),
//                                    Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (botIntentAnswer.AnswerType == AnswerTypeType.image)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = intentAnswerInChannel.Id,
//                                    Type = EnumAnswerType.image,
//                                    ImageId = Guid.Parse(botIntentAnswer.Answer.Split(Utils.GeneralSeparator)[1]),
//                                    Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (botIntentAnswer.AnswerType == AnswerTypeType.video)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = intentAnswerInChannel.Id,
//                                    Type = EnumAnswerType.video,
//                                    VideoUrl = botIntentAnswer.Answer,
//                                    Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (botIntentAnswer.AnswerType == AnswerTypeType.webhook)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = intentAnswerInChannel.Id,
//                                    Type = EnumAnswerType.webhook,
//                                    WebhookId = Guid.Parse(botIntentAnswer.Answer),
//                                    Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (botIntentAnswer.AnswerType == AnswerTypeType.complex)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = intentAnswerInChannel.Id,
//                                    Type = EnumAnswerType.complex,
//                                    Message = botIntentAnswer.Answer,
//                                    Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (botIntentAnswer.AnswerType == AnswerTypeType.quickReply)
//                            {
//                                var arr = botIntentAnswer.Answer.Split(Utils.GeneralSeparator);
//                                var message = arr[0];
//                                var quickReplyId = Guid.Parse(arr[1]);
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = intentAnswerInChannel.Id,
//                                    Type = EnumAnswerType.quickReply,
//                                    Message = message,
//                                    QuickReplyId = quickReplyId,
//                                    Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (botIntentAnswer.AnswerType == AnswerTypeType.button)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = intentAnswerInChannel.Id,
//                                    Type = EnumAnswerType.button,
//                                    Message = botIntentAnswer.Answer,
//                                    Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (botIntentAnswer.AnswerType == AnswerTypeType.viaForm)
//                            {
//                                response = new Response { };

//                                //Form
//                                string[] answerArr = botIntentAnswer.Answer.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.None);
//                                string formTitle = "";
//                                string formMessage = "";
//                                bool ifRequireConfirm = false;
//                                if(answerArr != null && answerArr.Length > 0)
//                                {
//                                    formTitle = answerArr[0];
//                                }
//                                if (answerArr != null && answerArr.Length > 1)
//                                {
//                                    formMessage = answerArr[1];
//                                }
//                                if (answerArr != null && answerArr.Length > 2)
//                                {
//                                    ifRequireConfirm = bool.Parse(answerArr[2]);
//                                }

//                                var form = new AnswerInChannelForm {
//                                    Id = Guid.NewGuid(),
//                                    Title = formTitle,
//                                    Message = formMessage,
//                                    IfRequireConfirm= ifRequireConfirm,                                    
//                                };
//                                answerInChannelFormDomainService.Create(form);

//                                response.Id = form.Id;
//                                intentAnswerInChannel.FormId = form.Id;
//                                var intentAnswerInChannelUpdateBo = Mapper.Map<IntentAnswerInChannelUpdateBo>(intentAnswerInChannel);
//                                intentAnswerInChannelDomainService.Update(intentAnswerInChannelUpdateBo);
//                            }

//                            if (response != null && response.Id != Guid.Empty)
//                            {
//                                botIntentAnswer.Id = response.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotIntentAnswerTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save intent answer fail");
//                            }
//                        }
//                        else if (type == typeof(BotIntentAnswerButtonTypeEx) && key.Contains('|') && key.Split('|').Length == 3)
//                        {
//                            //保存 t_Bot_IntentAnswerButtons
//                            string paramKey1 = key.Split('|')[0];
//                            string paramKey2 = key.Split('|')[1];
//                            BotIntentTypeEx botIntent = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotIntentTypeEx;
//                            BotIntentAnswerTypeEx botIntentAnswer = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey2]) as BotIntentAnswerTypeEx;

//                            BotIntentAnswerButtonTypeEx botIntentAnswerButton = data as BotIntentAnswerButtonTypeEx;
//                            botIntentAnswerButton.IntentId = botIntent.Id;
//                            botIntentAnswerButton.AnswerId = botIntentAnswer.Id;

//                            var intentAnswerButtons = Mapper.Map<ResponseButton>(botIntentAnswerButton);
//                            intentAnswerButtons = responseButtonDomainService.Create(intentAnswerButtons);
//                            if (intentAnswerButtons != null && intentAnswerButtons.Id != Guid.Empty)
//                            {
//                                botIntentAnswerButton.Id = intentAnswerButtons.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotIntentAnswerButtonTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save intent answer button fail");
//                            }
//                        }
//                        else if (type == typeof(BotIntentAnswerButtonTypeEx) && key.Contains('|') && key.Split('|').Length == 4)
//                        {
//                            //保存 t_Bot_IntentAnswerButtons
//                            string paramKey1 = key.Split('|')[0];
//                            string paramKey2 = key.Split('|')[1];
//                            string paramKey3 = key.Split('|')[2];
//                            BotIntentTypeEx botIntent = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotIntentTypeEx;
//                            BotIntentAnswerTypeEx botIntentAnswer = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey2]) as BotIntentAnswerTypeEx;
//                            BotIntentTypeEx botIntentEx = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey3]) as BotIntentTypeEx;

//                            BotIntentAnswerButtonTypeEx botIntentAnswerButton = data as BotIntentAnswerButtonTypeEx;
//                            botIntentAnswerButton.IntentId = botIntent.Id;
//                            botIntentAnswerButton.AnswerId = botIntentAnswer.Id;

//                            var intentAnswerButtons = Mapper.Map<ResponseButton>(botIntentAnswerButton);
//                            intentAnswerButtons.IntentId = botIntentEx.Id;

//                            intentAnswerButtons = responseButtonDomainService.Create(intentAnswerButtons);
//                            if (intentAnswerButtons != null && intentAnswerButtons.Id != Guid.Empty)
//                            {
//                                botIntentAnswerButton.Id = intentAnswerButtons.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotIntentAnswerButtonTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save intent answer button fail");
//                            }
//                        }
//                        else if (type == typeof(BotEntityCollectionFormFieldTypeEx) && key.Contains('|') && key.Split('|').Length == 3)
//                        {
//                            //保存 t_Bot_EntityCollectionFormFields
//                            string paramKey1 = key.Split('|')[0];
//                            string paramKey2 = key.Split('|')[1];
//                            BotIntentTypeEx botIntent = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotIntentTypeEx;
//                            BotIntentAnswerTypeEx botIntentAnswer = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey2]) as BotIntentAnswerTypeEx;
//                            BotEntityCollectionFormFieldTypeEx botEntityCollectionFormField = data as BotEntityCollectionFormFieldTypeEx;
//                            botEntityCollectionFormField.SiteId = botImportDataQueue.SiteId;
//                            botEntityCollectionFormField.IntentId = botIntent.Id;
//                            botEntityCollectionFormField.EntityId = Guid.Empty;
//                            botEntityCollectionFormField.AnswerId = botIntentAnswer.Id;

//                            var entityCollectionFormFields = Mapper.Map<AnswerInChannelFormField>(botEntityCollectionFormField);
//                            entityCollectionFormFields = answerInChannelFormFieldDomainService.Create(entityCollectionFormFields);
//                            if (entityCollectionFormFields != null && entityCollectionFormFields.Id != Guid.Empty)
//                            {
//                                botEntityCollectionFormField.Id = entityCollectionFormFields.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotEntityCollectionFormFieldTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save intent entity collection form field fail");
//                            }
//                        }
//                        else if (type == typeof(BotEntityCollectionFormFieldTypeEx) && key.Contains('|') && key.Split('|').Length == 4)
//                        {
//                            //保存 t_Bot_EntityCollectionFormFields
//                            string paramKey1 = key.Split('|')[0];
//                            string paramKey2 = key.Split('|')[1];
//                            string paramKey3 = key.Split('|')[2];
//                            BotIntentTypeEx botIntent = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotIntentTypeEx;
//                            BotEntityTypeEx botEntity = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey2]) as BotEntityTypeEx;
//                            BotIntentAnswerTypeEx botIntentAnswer = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey3]) as BotIntentAnswerTypeEx;
//                            BotEntityCollectionFormFieldTypeEx botEntityCollectionFormField = data as BotEntityCollectionFormFieldTypeEx;
//                            botEntityCollectionFormField.SiteId = botImportDataQueue.SiteId;
//                            botEntityCollectionFormField.IntentId = botIntent.Id;
//                            botEntityCollectionFormField.EntityId = botEntity.Id;
//                            botEntityCollectionFormField.AnswerId = botIntentAnswer.Id;

//                            var entityCollectionFormFields = Mapper.Map<AnswerInChannelFormField>(botEntityCollectionFormField);
//                            entityCollectionFormFields = answerInChannelFormFieldDomainService.Create(entityCollectionFormFields);
//                            if (entityCollectionFormFields != null && entityCollectionFormFields.Id != Guid.Empty)
//                            {
//                                botEntityCollectionFormField.Id = entityCollectionFormFields.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotEntityCollectionFormFieldTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save intent entity collection form field fail");
//                            }
//                        }
//                        else if (type == typeof(BotEntityCollectionPromptTypeEx))
//                        {
//                            //保存 t_Bot_EntityCollectionPrompts
//                            string paramKey1 = key.Split('|')[0];
//                            string paramKey2 = key.Split('|')[1];
//                            string paramKey3 = key.Split('|')[2];
//                            BotIntentTypeEx botIntent = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotIntentTypeEx;
//                            BotEntityTypeEx botEntity = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey2]) as BotEntityTypeEx;
//                            BotIntentAnswerTypeEx botIntentAnswer = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey3]) as BotIntentAnswerTypeEx;
                            
//                            if(intentAnswerInChannel == null)
//                            {
//                                intentAnswerInChannel = intentAnswerInChannelDomainService.GetByIntentIdAndChannel(botIntentAnswer.IntentId, botIntentAnswer.ChannelType);
//                                if (intentAnswerInChannel == null
//                                    || intentAnswerInChannel.Id == Guid.Empty)
//                                {
//                                    intentAnswerInChannel = new IntentAnswerInChannel
//                                    {
//                                        Id = Guid.NewGuid(),
//                                        IntentId = botIntentAnswer.IntentId,
//                                        Channel = botIntentAnswer.ChannelType,
//                                    };
//                                    intentAnswerInChannelDomainService.Create(intentAnswerInChannel);
//                                }
//                            }                            

//                            BotEntityCollectionPromptTypeEx botEntityCollectionPrompt = data as BotEntityCollectionPromptTypeEx;
//                            botEntityCollectionPrompt.IntentId = botIntent.Id;
//                            botEntityCollectionPrompt.EntityId = botEntity.Id;
//                            botEntityCollectionPrompt.AnswerId = botIntentAnswer.Id;

//                            var entityCollectionPrompts = Mapper.Map<AnswerInChannelPrompt>(botEntityCollectionPrompt);
//                            entityCollectionPrompts = answerInChannelPromptDomainService.Create(entityCollectionPrompts);
//                            if (entityCollectionPrompts != null && entityCollectionPrompts.Id != Guid.Empty)
//                            {
//                                botEntityCollectionPrompt.Id = entityCollectionPrompts.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotEntityCollectionPromptTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save intent entity collection prompt fail");
//                            }
//                        }
//                        else if (type == typeof(BotQuickReplyTypeEx))
//                        {
//                            //更新 t_Bot_QuickReply 数据 
//                            BotQuickReplyTypeEx botQuickReply = data as BotQuickReplyTypeEx;
//                            //string paramKey1 = key.Split('|')[0];
//                            //BotQuickReplyTypeEx botQuickReply = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotQuickReplyTypeEx;

//                            //botQuickReply.SiteId = botImportDataQueue.SiteId;
//                            //botQuickReply.BotId = botImportDataQueue.BotId;

//                            var quickReply = Mapper.Map<QuickReply>(botQuickReply);
//                            botQuickReply.SiteId = botImportDataQueue.SiteId;
//                            quickReply.BotId = botImportDataQueue.BotId;

//                            quickReply = quickReplyDomainService.Create(quickReply);
//                            if (quickReply != null && quickReply.Id != Guid.Empty)
//                            {
//                                botQuickReply.Id = quickReply.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotQuickReplyTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save bot quick reply fail");
//                            }
//                        }
//                        else if (type == typeof(BotQuickReplyItemTypeEx) && key.Contains('|') && key.Split('|').Length == 3)
//                        {
//                            //保存 t_Bot_QuickReplyItems
//                            string paramKey1 = key.Split('|')[0];
//                            string paramKey2 = key.Split('|')[1];
//                            BotQuickReplyTypeEx botQuickReply = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotQuickReplyTypeEx;
//                            BotIntentTypeEx botIntent = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey2]) as BotIntentTypeEx;

//                            BotQuickReplyItemTypeEx botQuickReplyItem = data as BotQuickReplyItemTypeEx;

//                            botQuickReplyItem.QuickReplyId = botQuickReply.Id;
//                            botQuickReplyItem.IntentId = botIntent.Id;

//                            var quickReplyItems = Mapper.Map<QuickReplyItem>(botQuickReplyItem);
//                            quickReplyItems = quickReplyItemDomainService.Create(quickReplyItems);
//                            if (quickReplyItems != null && quickReplyItems.Id != Guid.Empty)
//                            {
//                                botQuickReplyItem.Id = quickReplyItems.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotQuickReplyItemTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save bot quick reply item fail");
//                            }
//                        }
//                        else if (type == typeof(BotQuickReplyItemTypeEx) && key.Contains('|') && key.Split('|').Length == 2)
//                        {
//                            //保存 t_Bot_QuickReplyItems
//                            string paramKey1 = key.Split('|')[0];
//                            BotQuickReplyTypeEx botQuickReply = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotQuickReplyTypeEx;

//                            BotQuickReplyItemTypeEx botQuickReplyItem = data as BotQuickReplyItemTypeEx;

//                            botQuickReplyItem.QuickReplyId = botQuickReply.Id;

//                            var quickReplyItems = Mapper.Map<QuickReplyItem>(botQuickReplyItem);
//                            quickReplyItems = quickReplyItemDomainService.Create(quickReplyItems);
//                            if (quickReplyItems != null && quickReplyItems.Id != Guid.Empty)
//                            {
//                                botQuickReplyItem.Id = quickReplyItems.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotQuickReplyItemTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save bot quick reply item fail");
//                            }
//                        }
//                        else if (type == typeof(BotSmartTriggerTypeEx))
//                        {
//                            //更新 t_Bot_SmartTriggers 数据                     
//                            BotSmartTriggerTypeEx botSmartTrigger = data as BotSmartTriggerTypeEx;
//                            botSmartTrigger.SiteId = botImportDataQueue.SiteId;
//                            botSmartTrigger.BotId = botImportDataQueue.BotId;

//                            var smartTriggers = Mapper.Map<SmartTrigger>(botSmartTrigger);
//                            smartTriggers = smartTriggerDomainService.Create(smartTriggers);
//                            if (smartTriggers != null && smartTriggers.Id != Guid.Empty)
//                            {
//                                botSmartTrigger.Id = smartTriggers.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotSmartTriggerTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save bot smart trigger fail");
//                            }
//                        }
//                        else if (type == typeof(BotSmartTriggerConditionTypeEx))
//                        {
//                            //保存 t_Bot_SmartTriggerConditions
//                            string paramKey1 = key.Split('|')[0];
//                            BotSmartTriggerTypeEx botSmartTrigger = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotSmartTriggerTypeEx;

//                            BotSmartTriggerConditionTypeEx botSmartTriggerCondition = data as BotSmartTriggerConditionTypeEx;

//                            botSmartTriggerCondition.SmartTriggerId = botSmartTrigger.Id;

//                            var smartTriggerConditions = Mapper.Map<SmartTriggerCondition>(botSmartTriggerCondition);
//                            smartTriggerConditions = smartTriggerConditionDomainService.Create(smartTriggerConditions);
//                            if (smartTriggerConditions != null && smartTriggerConditions.Id != Guid.Empty)
//                            {
//                                botSmartTriggerCondition.Id = smartTriggerConditions.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotSmartTriggerConditionTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save bot smart trigger condition fail");
//                            }
//                        }
//                        else if (type == typeof(BotSmartTriggerActionTypeEx))
//                        {
//                            //保存 t_Bot_SmartTriggerActions
//                            string paramKey1 = key.Split('|')[0];
//                            BotSmartTriggerTypeEx botSmartTrigger = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotSmartTriggerTypeEx;

//                            BotSmartTriggerActionTypeEx botSmartTriggerAction = data as BotSmartTriggerActionTypeEx;

//                            botSmartTriggerAction.SmartTriggerId = botSmartTrigger.Id;

//                            var smartTriggerActions = Mapper.Map<SmartTriggerAction>(botSmartTriggerAction);
//                            smartTriggerActions = smartTriggerActionDomainService.Create(smartTriggerActions);
//                            if (smartTriggerActions != null && smartTriggerActions.Id != Guid.Empty)
//                            {
//                                botSmartTriggerAction.Id = smartTriggerActions.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "BotSmartTriggerActionTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save bot smart trigger action fail");
//                            }
//                        }
//                        else if (type == typeof(AnswerTypeEx) && !key.Contains('|'))
//                        {
//                            //保存 t_Bot_IntentAnswers greeting message text
//                            AnswerTypeEx answerTypeEx = data as AnswerTypeEx;
//                            answerTypeEx.SiteId = botImportDataQueue.SiteId;
//                            answerTypeEx.BotId = botImportDataQueue.BotId;
//                            answerTypeEx.IntentId = Guid.Empty;                            
                            
//                            if(greetingMessageInChannel == null)
//                            {
//                                greetingMessageInChannel = greetingMessageInChannelDomainService.GetByBotIdAndChannel(botImportDataQueue.BotId, answerTypeEx.ChannelType);
//                                if(greetingMessageInChannel == null
//                                    || greetingMessageInChannel.Id == Guid.Empty)
//                                {
//                                    greetingMessageInChannel = new GreetingMessageInChannel {
//                                        Id = Guid.NewGuid(),
//                                        BotId = botImportDataQueue.BotId,
//                                        Channel = answerTypeEx.ChannelType,
//                                    };
//                                    greetingMessageInChannelDomainService.Create(greetingMessageInChannel);
//                                }
//                            }

//                            Response response = null;
//                            if (answerTypeEx.Type == AnswerTypeType.text)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.text,
//                                    TextVariants = JsonConvert.SerializeObject(answerTypeEx.Content.Split(Utils.GeneralSeparator)),
//                                    //Order = answerTypeEx.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (answerTypeEx.Type == AnswerTypeType.image)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.image,
//                                    ImageId = Guid.Parse(answerTypeEx.Content.Split(Utils.GeneralSeparator)[1]),
//                                    //Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (answerTypeEx.Type == AnswerTypeType.video)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.video,
//                                    VideoUrl = answerTypeEx.Content,
//                                    //Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (answerTypeEx.Type == AnswerTypeType.webhook)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.webhook,
//                                    WebhookId = Guid.Parse(answerTypeEx.Content),
//                                    //Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (answerTypeEx.Type == AnswerTypeType.complex)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.complex,
//                                    Message = answerTypeEx.Content,
//                                    //Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (answerTypeEx.Type == AnswerTypeType.quickReply)
//                            {
//                                var arr = answerTypeEx.Content.Split(Utils.GeneralSeparator);
//                                var message = arr[0];
//                                var quickReplyId = Guid.Parse(arr[1]);
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.quickReply,
//                                    Message = message,
//                                    QuickReplyId = quickReplyId,
//                                    //Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }

//                            if (response != null && response.Id != Guid.Empty)
//                            {
//                                answerTypeEx.Id = response.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "AnswerTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save intent answer fail");
//                            }
//                        }
//                        else if (type == typeof(ButtonTypeEx) && key.Contains('|') && key.Split('|').Length == 3)
//                        {
//                            //保存 t_Bot_IntentAnswerButtons greeting message button quick reply
//                            string paramKey1 = key.Split('|')[0];
//                            string paramKey2 = key.Split('|')[1];
//                            AnswerTypeEx answerTypeEx = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as AnswerTypeEx;
//                            BotIntentTypeEx botIntentTypeEx = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey2]) as BotIntentTypeEx;

//                            ButtonTypeEx buttonTypeEx = data as ButtonTypeEx;
//                            buttonTypeEx.IntentId = answerTypeEx.IntentId;
//                            buttonTypeEx.AnswerId = answerTypeEx.Id;

//                            var intentAnswerButtons = Mapper.Map<ResponseButton>(buttonTypeEx);
//                            intentAnswerButtons.IntentId = botIntentTypeEx.Id;

//                            intentAnswerButtons = responseButtonDomainService.Create(intentAnswerButtons);
//                            if (intentAnswerButtons != null && intentAnswerButtons.Id != Guid.Empty)
//                            {
//                                buttonTypeEx.Id = intentAnswerButtons.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "ButtonTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save intent answer button fail");
//                            }
//                        }
//                        else if (type == typeof(ButtonTypeEx) && key.Contains('|') && key.Split('|').Length == 2)
//                        {
//                            //保存 t_Bot_IntentAnswerButtons
//                            string paramKey1 = key.Split('|')[0];
//                            AnswerTypeEx answerTypeEx = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as AnswerTypeEx;

//                            ButtonTypeEx buttonTypeEx = data as ButtonTypeEx;

//                            buttonTypeEx.IntentId = answerTypeEx.IntentId;
//                            buttonTypeEx.AnswerId = answerTypeEx.Id;

//                            var intentAnswerButtons = Mapper.Map<ResponseButton>(buttonTypeEx);

//                            intentAnswerButtons = responseButtonDomainService.Create(intentAnswerButtons);
//                            if (intentAnswerButtons != null && intentAnswerButtons.Id != Guid.Empty)
//                            {
//                                buttonTypeEx.Id = intentAnswerButtons.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "ButtonTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save intent answer button fail");
//                            }
//                        }
//                        else if (type == typeof(UnrecognizedMessageTypeEx) && key.Contains("NoAnswerMessage|"))
//                        {
//                            //保存 t_Bot_NoAnswerMessageInChannel

//                            UnrecognizedMessageTypeEx unrecognizedMessageTypeEx = data as UnrecognizedMessageTypeEx;

//                            unrecognizedMessageTypeEx.BotId = botImportDataQueue.BotId;

//                            var noAnswerMessageInChannel = Mapper.Map<NoAnswerMessageInChannel>(unrecognizedMessageTypeEx);

//                            noAnswerMessageInChannel = noAnswerMessageInChannelDomainService.Create(noAnswerMessageInChannel);
//                            if (noAnswerMessageInChannel != null && noAnswerMessageInChannel.Id != Guid.Empty)
//                            {
//                                unrecognizedMessageTypeEx.Id = noAnswerMessageInChannel.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "UnrecognizedMessageTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save noAnswerMessageInChannel fail");
//                            }
//                        }
//                        else if (type == typeof(UnrecognizedMessageTypeEx) && key.Contains("PossibleAnswerMessage|"))
//                        {
//                            //保存 t_Bot_PossibleAnswerMessageInChannel
//                            UnrecognizedMessageTypeEx unrecognizedMessageTypeEx = data as UnrecognizedMessageTypeEx;

//                            unrecognizedMessageTypeEx.BotId = botImportDataQueue.BotId;

//                            var possibleAnswerMessageInChannel = Mapper.Map<MessageAfterSeveralConsecutivePossibleAnswersInChannel>(unrecognizedMessageTypeEx);

//                            possibleAnswerMessageInChannel = messageAfterSeveralConsecutivePossibleAnswersInChannelDomainService.Create(possibleAnswerMessageInChannel);
//                            if (possibleAnswerMessageInChannel != null && possibleAnswerMessageInChannel.Id != Guid.Empty)
//                            {
//                                unrecognizedMessageTypeEx.Id = possibleAnswerMessageInChannel.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "UnrecognizedMessageTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save possibleAnswerMessageInChannel fail");
//                            }
//                        }
//                        else if (type == typeof(AnswerTypeEx) && key.Contains('|'))
//                        {
//                            //保存 t_Bot_IntentAnswers greeting message quick reply
//                            string paramKey1 = key.Split('|')[0];
//                            BotQuickReplyTypeEx botQuickReplyTypeEx = GetQueueObject(botImportDataQueue.ObjectMaps[paramKey1]) as BotQuickReplyTypeEx;

//                            AnswerTypeEx answerTypeEx = data as AnswerTypeEx;

//                            string[] arr = answerTypeEx.Content.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.RemoveEmptyEntries);
//                            //answerTypeEx.Content = string.Join(Utils.GeneralSeparator, arr[0], botQuickReplyTypeEx.Id);

//                            answerTypeEx.SiteId = botImportDataQueue.SiteId;
//                            answerTypeEx.BotId = botImportDataQueue.BotId;
//                            answerTypeEx.IntentId = Guid.Empty;

//                            if (greetingMessageInChannel == null)
//                            {
//                                greetingMessageInChannel = greetingMessageInChannelDomainService.GetByBotIdAndChannel(botImportDataQueue.BotId, answerTypeEx.ChannelType);
//                                if (greetingMessageInChannel == null
//                                    || greetingMessageInChannel.Id == Guid.Empty)
//                                {
//                                    greetingMessageInChannel = new GreetingMessageInChannel
//                                    {
//                                        Id = Guid.NewGuid(),
//                                        BotId = botImportDataQueue.BotId,
//                                        Channel = answerTypeEx.ChannelType,
//                                    };
//                                    greetingMessageInChannelDomainService.Create(greetingMessageInChannel);
//                                }
//                            }

//                            Response response = null;
//                            if (answerTypeEx.Type == AnswerTypeType.text)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.text,
//                                    TextVariants = JsonConvert.SerializeObject(answerTypeEx.Content.Split(Utils.GeneralSeparator)),
//                                    //Order = answerTypeEx.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (answerTypeEx.Type == AnswerTypeType.image)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.image,
//                                    ImageId = Guid.Parse(answerTypeEx.Content.Split(Utils.GeneralSeparator)[1]),
//                                    //Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (answerTypeEx.Type == AnswerTypeType.video)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.video,
//                                    VideoUrl = answerTypeEx.Content,
//                                    //Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (answerTypeEx.Type == AnswerTypeType.webhook)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.webhook,
//                                    WebhookId = Guid.Parse(answerTypeEx.Content),
//                                    //Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (answerTypeEx.Type == AnswerTypeType.complex)
//                            {
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.complex,
//                                    Message = answerTypeEx.Content,
//                                    //Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }
//                            else if (answerTypeEx.Type == AnswerTypeType.quickReply)
//                            {
//                                var message = arr[0];
//                                var quickReplyId = Guid.Parse(arr[1]);
//                                response = new Response
//                                {
//                                    Id = Guid.NewGuid(),
//                                    ParentId = greetingMessageInChannel.Id,
//                                    Type = EnumAnswerType.quickReply,
//                                    Message = message,
//                                    QuickReplyId = quickReplyId,
//                                    //Order = botIntentAnswer.Sort,
//                                };
//                                responseDomainService.Create(response);
//                            }

//                            if (response != null && response.Id != Guid.Empty)
//                            {
//                                answerTypeEx.Id = response.Id;
//                                botImportDataQueue.ObjectMaps[lastKey] = new { ObjectType = "AnswerTypeEx", Object = data };
//                            }
//                            else
//                            {
//                                throw new Exception("save intent answer fail");
//                            }
//                        }

//                        index++;
//                    }
//                }
//                if (botImportDataQueue.ImportDataQueue.Count == 0)
//                {
//                    botImportDataQueue.Status = EnumImportHandleStatus.Publish;
//                }
//                else
//                {
//                    botImportDataQueue.Status = EnumImportHandleStatus.Processing;
//                }
//            }
//            catch (Exception e)
//            {
//                LogHelper.Error(JsonConvert.SerializeObject(e));
//                errorMessage = e.Message;
//            }
//            finally
//            {

//            }

//            return errorMessage;
//        }
//        private string ReadResourceFile(string fileName)
//        {
//            Assembly assembly = Assembly.Load("Bot.WebApi");
//            string projectName = assembly.GetName().Name;
//            string resourceName = string.Format("{0}.App_Data.BotImport.{1}", projectName, fileName);
//            using (Stream sm = assembly.GetManifestResourceStream(resourceName))
//            using (StreamReader sr = new StreamReader(sm))
//            {
//                return sr.ReadToEnd();
//            }
//        }
//        //private int CreateCategory(int siteId, Guid botId, string category)
//        //{
//        //    //返回最后一个新增cagegory Id 值

//        //    int categoryId = -1;

//        //    if (string.IsNullOrEmpty(category))
//        //    {
//        //        return -1;
//        //    }

//        //    BotCatagoryDto rootCatagoryDto = _botCatagoryService.GetRootCatagory(botId);
//        //    if (rootCatagoryDto != null && rootCatagoryDto.Id != Guid.Empty)
//        //    {
//        //        categoryId = rootCatagoryDto.Id;
//        //    }
//        //    else
//        //    {
//        //        rootCatagoryDto = _botCatagoryService.InsertRootCategory(new BotCatagoryDto
//        //        {
//        //            SiteId = siteId,
//        //            BotId = botId,
//        //            ParentId = 0,
//        //            Name = "/"
//        //        });
//        //        categoryId = rootCatagoryDto.Id;
//        //    }

//        //    int parentId = rootCatagoryDto.Id;
//        //    string[] categoryArr = category.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
//        //    for (int i = 0; i < categoryArr.Length; i++)
//        //    {
//        //        string categoryName = categoryArr[i];
//        //        BotCatagoryDto botCatagoryDto = _botCatagoryService.GetCatagory(botId, parentId, categoryName);
//        //        if (botCatagoryDto != null)
//        //        {

//        //        }
//        //        else
//        //        {
//        //            //创建
//        //            BotCatagoryDto newBotCatagoryDto = new BotCatagoryDto
//        //            {
//        //                SiteId = siteId,
//        //                BotId = botId,
//        //                ParentId = parentId,
//        //                Name = categoryName
//        //            };
//        //            botCatagoryDto = _botCatagoryService.Insert(newBotCatagoryDto);
//        //            if (botCatagoryDto != null && botCatagoryDto.Id != Guid.Empty) { }
//        //            else
//        //            {
//        //                LogHelper.Error(string.Format("Create category fail[{0}]", JsonConvert.SerializeObject(newBotCatagoryDto)));
//        //                throw new Exception(string.Format("Create category fail"));
//        //            }
//        //        }

//        //        categoryId = botCatagoryDto.Id;
//        //        parentId = botCatagoryDto.Id;
//        //    }

//        //    return categoryId;
//        //}
//        /// <summary>
//        /// 导入前删除Bot下所有的数据
//        /// </summary>
//        /// <param name="siteId"></param>
//        /// <param name="botId"></param>
//        private string DeleteBotInfo(Chatbot bot)
//        {
//            string errorMessage = "";
//            try
//            {
//                Delete(bot.Id);
//            }
//            catch (Exception e)
//            {
//                LogHelper.Error(string.Format("DeleteBotInfo [Exception:{0},StackTrace:{1}]", e.Message, e.StackTrace));
//                errorMessage = e.Message;
//            }
//            finally
//            {

//            }

//            return errorMessage;
//        }

//        //由于Intent 类结构改变，此处需要作出修改。待该
//        private string ReplaceIntentResponseText(int siteid, Guid botId)
//        {
//            string errorMessage = "";
//            try
//            {
//                IIntentDomainService intentDomainService = _container.Resolve<IIntentDomainService>();
//                IQuickReplyDomainService quickReplyDomainService = _container.Resolve<IQuickReplyDomainService>();
//                IGreetingMessageInChannelDomainService greetingMessageInChannelDomainService = _container.Resolve<IGreetingMessageInChannelDomainService>();
//                IResponseDomainService responseDomainService = _container.Resolve<IResponseDomainService>();

//                bool firstExe = true;
//                string pattern = @"<a title=.*?>([^<]+?)</a>";
//                var botIntentsList = intentDomainService.List(botId, "", null, "");
//                //List<BotIntents> botIntentsMatchList = botIntentsList.Where(a => !string.IsNullOrEmpty(a.ResponseText) && Regex.IsMatch(a.ResponseText, pattern)).ToList();
//                var quickReplyList = quickReplyDomainService.List(botId, "");
//                foreach (var botIntents in botIntentsList)
//                {
//                    //if (!string.IsNullOrEmpty(botIntents.ResponseText) && Regex.IsMatch(botIntents.ResponseText, pattern))
//                    //{
//                    //    string str = botIntents.ResponseText;
//                    //    Regex reg = new Regex(pattern);
//                    //    MatchCollection matchCollection = reg.Matches(str);
//                    //    if (matchCollection != null && matchCollection.Count > 0)
//                    //    {
//                    //        foreach (Match match in matchCollection)
//                    //        {
//                    //            string data = match.Groups[1].Value;
//                    //            BotIntents botIntentsFind = botIntentsList.FirstOrDefault(a => a.IntentName == data);
//                    //            if (botIntentsFind != null && botIntentsFind.Id != Guid.Empty)
//                    //            {
//                    //                string aHtml = match.Value;
//                    //                aHtml = Regex.Replace(aHtml, "intentId=\\d+", string.Format("intentId={0}", botIntentsFind.Id));
//                    //                aHtml = Regex.Replace(aHtml, "intentid=\"\\d+\"", string.Format("intentid=\"{0}\"", botIntentsFind.Id));
//                    //                str = str.Replace(match.Value, aHtml);
//                    //            }
//                    //        }

//                    //        botIntents.ResponseText = str;
//                    //        _intentDomainService.Update(botIntents);
//                    //    }
//                    //}

//                    //修改IntentAnswers中类型为 quickreply的quickReplyName为ID
//                    var intentAnswersList = intentDomainService.GetResponsesByIntentId(botIntents.Id);
//                    if (firstExe)
//                    {
//                        var intentAnswersListGreeting = greetingMessageInChannelDomainService.GetByBotId(botId, "responses").SelectMany(a=>a.Responses);
//                        intentAnswersList = intentAnswersList.Concat(intentAnswersListGreeting).ToList();
//                    }

//                    firstExe = false;

//                    if (intentAnswersList != null)
//                    {
//                        foreach (var intentAnswers in intentAnswersList)
//                        {
//                            bool ifUpdate = false;

//                            //if (intentAnswers.AnswerType == EnumAnswerType.quickReply.ToString())
//                            //{
//                            //    string[] quickReplayArr = intentAnswers.Answer.Split(new string[] { Utils.GeneralSeparator }, StringSplitOptions.None);
//                            //    string quickReplayName = quickReplayArr?[1];
//                            //    QuickReply quickReply = quickReplyList.FirstOrDefault(a => a.Name == quickReplayName);
//                            //    intentAnswers.Answer = string.Join(Utils.GeneralSeparator, new object[] { quickReplayArr?[0], quickReply?.Id });

//                            //    _intentAnswersService.Update(intentAnswers);
//                            //}
                            
//                            if (intentAnswers.Type == EnumAnswerType.htmlText)
//                            {
//                                //可能里面包含 link gotoIntent 
//                                if (!string.IsNullOrEmpty(intentAnswers.HtmlTextVariants))
//                                {
//                                    string content = intentAnswers.HtmlTextVariants;

//                                    pattern = "<a href=.*?>([^<]+?)</a>";
//                                    bool ifMatch = Regex.IsMatch(content, pattern);
//                                    if (ifMatch)
//                                    {
//                                        Regex regex = new Regex(pattern);
//                                        MatchCollection matchCollection = regex.Matches(content);
//                                        foreach (Match match in matchCollection)
//                                        {
//                                            string html = match.Groups[0].Value;
//                                            string dataLinkType = Utils.GetTitleContent(html, "a", "data-linktype");
//                                            if (dataLinkType == "1")
//                                            {
//                                                string intentname = Utils.GetTitleContent(html, "a", "data-intentname");
//                                                if (!string.IsNullOrEmpty(intentname))
//                                                {
//                                                    //判断 intent 是否存在
//                                                    var botIntentFind = botIntentsList.FirstOrDefault(a => a.Name == intentname);
//                                                    if (botIntentFind != null && botIntentFind.Id != Guid.Empty)
//                                                    {
//                                                        string replace = Regex.Replace(html, "data-intentid=\"\\d+\"", string.Format("data-intentid=\"{0}\"", botIntentFind.Id));
//                                                        content = content.Replace(html, replace);
//                                                        ifUpdate = true;
//                                                    }
//                                                }
//                                            }
//                                        }

//                                        if (ifUpdate)
//                                        {
//                                            intentAnswers.HtmlTextVariants = content;
//                                            var responseUpdateBo = Mapper.Map<ResponseUpdateBo>(intentAnswers);
//                                            responseDomainService.Update(responseUpdateBo);
//                                        }

//                                    }
//                                }
//                            }
//                            else if (intentAnswers.Type == EnumAnswerType.complex)
//                            {
//                                //可能里面包含 link gotoIntent 
//                                if (!string.IsNullOrEmpty(intentAnswers.HtmlTextVariants))
//                                {
//                                    string content = intentAnswers.HtmlTextVariants;

//                                    pattern = @"<a title=.*?>([^<]+?)</a>";
//                                    bool ifMatch = Regex.IsMatch(content, pattern);
//                                    if (ifMatch)
//                                    {
//                                        Regex reg = new Regex(pattern);
//                                        MatchCollection matchCollection = reg.Matches(content);
//                                        if (matchCollection != null && matchCollection.Count > 0)
//                                        {
//                                            foreach (Match match in matchCollection)
//                                            {
//                                                string html = match.Value;
//                                                string dataLinkType = Utils.GetTitleContent(html, "a", "data-linktype");
//                                                if (dataLinkType == "1")
//                                                {
//                                                    string intentName = Utils.GetTitleContent(html, "a", "data-intentname");
//                                                    var botIntentsFind = botIntentsList.FirstOrDefault(a => a.Name == intentName);
//                                                    if (botIntentsFind != null && botIntentsFind.Id != Guid.Empty)
//                                                    {

//                                                    }
//                                                    else
//                                                    {
//                                                        string data = match.Groups[1].Value;
//                                                        botIntentsFind = botIntentsList.FirstOrDefault(a => a.Name == data);
//                                                    }

//                                                    if (botIntentsFind != null && botIntentsFind.Id != Guid.Empty)
//                                                    {
//                                                        string aHtml = match.Value;
//                                                        aHtml = Regex.Replace(aHtml, "intentId=\\d+", string.Format("intentId={0}", botIntentsFind.Id));
//                                                        aHtml = Regex.Replace(aHtml, "intentid=\"\\d+\"", string.Format("intentid=\"{0}\"", botIntentsFind.Id));
//                                                        content = content.Replace(match.Value, aHtml);
//                                                        ifUpdate = true;
//                                                    }
//                                                }
//                                            }

//                                            if (ifUpdate)
//                                            {
//                                                intentAnswers.HtmlTextVariants = content;
//                                                var responseUpdateBo = Mapper.Map<ResponseUpdateBo>(intentAnswers);
//                                                responseDomainService.Update(responseUpdateBo);
//                                            }
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//            catch (Exception e)
//            {
//                LogHelper.Error(JsonConvert.SerializeObject(e));
//                errorMessage = e.Message;
//            }
//            finally
//            {

//            }
//            return errorMessage;
//        }

//        #endregion
    }
}
